如何将画布内容转换为图像?

2024-05-16 09:17:22 发布

您现在位置:Python中文网/ 问答频道 /正文

from Tkinter import *
root = Tk()
cv = Canvas(root)
cv.create_rectangle(10,10,50,50)
cv.pack()
root.mainloop()

我想将画布内容转换为位图或其他图像,然后执行其他操作,如旋转或缩放图像,或更改其坐标。

如果我不再画图,位图可以提高显示效率。

我该怎么办?


Tags: from图像import内容tkinter画布createroot
3条回答

使用枕头将Postscript转换为PNG

from PIL import Image

def save_as_png(canvas,fileName):
    # save postscipt image 
    canvas.postscript(file = fileName + '.eps') 
    # use PIL to convert to PNG 
    img = Image.open(fileName + '.eps') 
    img.save(fileName + '.png', 'png') 

我找到了一个很好的方法来做这件事,真的很有帮助。为此,您需要PIL模块。代码如下:

from PIL import ImageGrab

def getter(widget):
    x=root.winfo_rootx()+widget.winfo_x()
    y=root.winfo_rooty()+widget.winfo_y()
    x1=x+widget.winfo_width()
    y1=y+widget.winfo_height()
    ImageGrab.grab().crop((x,y,x1,y1)).save("file path here")

这样做的目的是向函数传递一个小部件名称。命令root.winfo_rootx()root.winfo_rooty()获取整个root窗口左上角的像素位置。

然后,将widget.winfo_x()widget.winfo_y()添加到中,基本上只需获得要捕获的小部件左上角像素的像素坐标(在屏幕的像素(x,y)处)。

然后我找到(x1,y1),它是小部件左下角的像素。ImageGrab.grab()生成一个printscreen,然后我将其裁剪为只获取包含小部件的位。虽然不是完美的,也不会产生最好的图像,但这是一个很好的工具,只需获取任何小部件的图像并保存它。

如果你有任何问题,请发表评论!希望这有帮助!

您可以生成postscript文档(以馈送到其他工具:ImageMagick、Ghostscript等):

from Tkinter import *
root = Tk()
cv = Canvas(root)
cv.create_rectangle(10,10,50,50)
cv.pack()
root.mainloop()

cv.update()
cv.postscript(file="file_name.ps", colormode='color')

root.mainloop()

或者在PIL和Tkinter的画布上并行绘制相同的图像(请参见:Saving a Tkinter Canvas Drawing (Python))。例如(受同一篇文章启发):

from Tkinter import *
import Image, ImageDraw

width = 400
height = 300
center = height//2
white = (255, 255, 255)
green = (0,128,0)

root = Tk()

# Tkinter create a canvas to draw on
cv = Canvas(root, width=width, height=height, bg='white')
cv.pack()

# PIL create an empty image and draw object to draw on
# memory only, not visible
image1 = Image.new("RGB", (width, height), white)
draw = ImageDraw.Draw(image1)

# do the Tkinter canvas drawings (visible)
cv.create_line([0, center, width, center], fill='green')

# do the PIL image/draw (in memory) drawings
draw.line([0, center, width, center], green)

# PIL image can be saved as .png .jpg .gif or .bmp file (among others)
filename = "my_drawing.jpg"
image1.save(filename)

root.mainloop()

相关问题 更多 >