如何将画布内容转换为图像? [英] How can I convert canvas content to an image?

查看:47
本文介绍了如何将画布内容转换为图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I want to convert canvas content to a bitmap or other image, and then do other operations, such as rotating or scaling the image, or changing its coordinates.

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

Bitmaps can improve efficiency to show if I am no longer drawing.

我该怎么办?

推荐答案

您可以生成 postscript 文档(以提供给其他一些工具:ImageMagick、Ghostscript 等):

You can either generate a postscript document (to feed into some other tool: ImageMagick, Ghostscript, etc):

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 的画布上并行绘制相同的图像(参见:保存 Tkinter 画布绘图 (Python)).例如(灵感来自同一篇文章):

or draw the same image in parallel on PIL and on Tkinter's canvas (see: Saving a Tkinter Canvas Drawing (Python)). For example (inspired by the same article):

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

这篇关于如何将画布内容转换为图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆