insert text on image, python

有些话、适合烂在心里 提交于 2019-12-24 08:51:28

问题


My project is about loading an image and when I click on a button, a text area appears in the image, and I can write a text on it and later on save the text written on the image and the image. To do so I used tkinter but I set my image as background and I added a text box(text widget) and enter a text, but obviously I can't save that image( the one set as background) and the text written on it. I tried using PIL but i didn't find what I was looking for. This is my code using tkinter :

from tkinter import *
from PIL import ImageTk
import cv2

#root = Tk()

image=cv2.imread("New_refImg.png")
width_1, height_1,channels = image.shape   
print(width_1)
print(height_1)

canvas = Canvas(width =height_1, height = width_1, bg = 'blue')
canvas.pack(expand = 1, fill = BOTH)

img = ImageTk.PhotoImage(file = "New_refImg.png")

canvas.create_image(0, 0, image = img, anchor = NW)

#Add text
entry = Entry(canvas, width=12)
entry.pack(side=BOTTOM,padx=43,pady=height_1-130) # "side" position button

def onok():    
    x= entry.get().split('x')
    print(x)

Button(canvas, text='OK', command=onok).pack(side=LEFT)

mainloop()

回答1:


So, you could draw text into your canvas - Python: how to add text inside a canvas? - and then convert that canvas to an image for saving - How can I convert canvas content to an image?

However, I would instead recommend using PIL/Pillow. You can draw text onto an image - https://pillow.readthedocs.io/en/5.2.x/reference/ImageDraw.html#example-draw-partial-opacity-text. You can provide the Pillow image to ImageTk.PhotoImage directly as an argument - ImageTk.PhotoImage(im). You can naturally save the image to a file - http://pillow.readthedocs.io/en/5.2.x/reference/Image.html#PIL.Image.Image.save



来源:https://stackoverflow.com/questions/50352381/insert-text-on-image-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!