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

问题描述 投票:17回答:4
from Tkinter import *
root = Tk()
cv = Canvas(root)
cv.create_rectangle(10,10,50,50)
cv.pack()
root.mainloop()

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

位图可以提高效率,以显示我是否不再绘图。

我该怎么办?

python bitmap tkinter
4个回答
21
投票

您可以生成一个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()

或者在PILL和Tkinter画布上并行绘制相同的图像(参见:qazxsw poi)。例如(受同一篇文章的启发):

Saving a Tkinter Canvas Drawing (Python)

15
投票

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

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()

这样做是将小部件名称传递给函数。命令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()窗口左上角的像素位置。

然后,添加rootwidget.winfo_x(),基本上只是获取要捕获的小部件的左上角像素的像素坐标(在屏幕的像素(x,y)处)。

然后我找到(x1,y1)这是小部件的左下角像素。 widget.winfo_y()制作了一个版画屏幕,然后我将其裁剪为仅包含小部件的位。虽然不完美,并且不会产生最佳图像,但这是一个很好的工具,只需获取任何小部件的图像并保存它。

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


0
投票

也许您可以尝试使用widget_winfo_id来获取画布的HWND。

ImageGrab.grab()

-1
投票

使用Pillow从Postscript转换为PNG

import win32gui

from PIL import ImageGrab

HWND = canvas.winfo_id()  # get the handle of the canvas

rect = win32gui.GetWindowRect(HWND)  # get the coordinate of the canvas

im = ImageGrab.grab(rect)  # get image of the current location
© www.soinside.com 2019 - 2024. All rights reserved.