如何将 Python tkinter canvas postscript 文件转换为 PIL 可读的图像文件?
How to convert a Python tkinter canvas postscript file to an image file readable by the PIL?
所以我在我的程序中创建了一个函数,允许用户将 he/she 在 Turtle canvas 上绘制的任何内容保存为具有 his/her 自己名称的 Postscript 文件。但是,根据 Postscript 文件的性质,有些颜色不会出现在输出中,而且 Postscript 文件在其他一些平台上也无法打开。所以我决定将 postscript 文件保存为 JPEG 图像,因为 JPEG 文件应该能够在许多平台上打开,有望显示 canvas 的所有颜色,并且它应该具有比后记文件。因此,为此,我尝试使用 PIL,在我的保存函数中执行以下操作:
def savefirst():
cnv = getscreen().getcanvas()
global hen
fev = cnv.postscript(file = 'InitialFile.ps', colormode = 'color')
hen = filedialog.asksaveasfilename(defaultextension = '.jpg')
im = Image.open(fev)
print(im)
im.save(hen + '.jpg')
然而,每当我 运行 这个,我得到这个错误:
line 2391, in savefirst
im = Image.open(fev)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 2263, in open
fp = io.BytesIO(fp.read())
AttributeError: 'str' object has no attribute 'read'
显然它无法读取 postscript 文件,因为它 不是 ,据我所知,它本身就是一个图像,因此必须先将其转换为图像,然后再读取作为图像,然后最终转换并保存为 JPEG 文件。 问题是,我如何能够首先将后记文件转换为图像文件在程序内部可能使用Python 成像库? 环顾 SO 和 Google 没有任何帮助,因此非常感谢 SO 用户的任何帮助!
编辑: 遵循 unubuntu's
建议,我的保存功能现在有了这个:
def savefirst():
cnv = getscreen().getcanvas()
global hen
ps = cnv.postscript(colormode = 'color')
hen = filedialog.asksaveasfilename(defaultextension = '.jpg')
im = Image.open(io.BytesIO(ps.encode('utf-8')))
im.save(hen + '.jpg')
然而,现在每当我 运行 那个,我得到这个错误:
line 2395, in savefirst
im.save(hen + '.jpg')
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 1646, in save
self.load()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/EpsImagePlugin.py", line 337, in load
self.im = Ghostscript(self.tile, self.size, self.fp, scale)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/EpsImagePlugin.py", line 143, in Ghostscript
stdout=subprocess.PIPE)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 1544, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'gs'
什么是 'gs'
以及为什么我现在收到此错误?
If you don't supply the file parameter 在对 cnv.postscript
的调用中,然后
a cnv.postscript
returns 作为 (unicode) 字符串的 PostScript。
然后您可以将 unicode 转换为字节并将其提供给 io.BytesIO
并将其提供给 Image.open
。 Image.open
可以接受任何实现 read
、seek
和 tell
方法的 file-like 对象作为其第一个参数。
import io
def savefirst():
cnv = getscreen().getcanvas()
global hen
ps = cnv.postscript(colormode = 'color')
hen = filedialog.asksaveasfilename(defaultextension = '.jpg')
im = Image.open(io.BytesIO(ps.encode('utf-8')))
im.save(hen + '.jpg')
比如大量借鉴A. Rodas' code,
import Tkinter as tk
import subprocess
import os
import io
from PIL import Image
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.line_start = None
self.canvas = tk.Canvas(self, width=300, height=300, bg="white")
self.canvas.bind("<Button-1>", lambda e: self.draw(e.x, e.y))
self.button = tk.Button(self, text="save",
command=self.save)
self.canvas.pack()
self.button.pack(pady=10)
def draw(self, x, y):
if self.line_start:
x_origin, y_origin = self.line_start
self.canvas.create_line(x_origin, y_origin, x, y)
self.line_start = x, y
def save(self):
ps = self.canvas.postscript(colormode='color')
img = Image.open(io.BytesIO(ps.encode('utf-8')))
img.save('/tmp/test.jpg')
app = App()
app.mainloop()
添加到unutbu的答案中,您还可以将数据再次写入BytesIO对象,但是这样做之后您必须寻找到缓冲区的开头。这是一个在浏览器中显示图像的烧瓶示例:
@app.route('/image.png', methods=['GET'])
def image():
"""Return png of current canvas"""
ps = tkapp.canvas.postscript(colormode='color')
out = BytesIO()
Image.open(BytesIO(ps.encode('utf-8'))).save(out, format="PNG")
out.seek(0)
return send_file(out, mimetype='image/png')
所以我在我的程序中创建了一个函数,允许用户将 he/she 在 Turtle canvas 上绘制的任何内容保存为具有 his/her 自己名称的 Postscript 文件。但是,根据 Postscript 文件的性质,有些颜色不会出现在输出中,而且 Postscript 文件在其他一些平台上也无法打开。所以我决定将 postscript 文件保存为 JPEG 图像,因为 JPEG 文件应该能够在许多平台上打开,有望显示 canvas 的所有颜色,并且它应该具有比后记文件。因此,为此,我尝试使用 PIL,在我的保存函数中执行以下操作:
def savefirst():
cnv = getscreen().getcanvas()
global hen
fev = cnv.postscript(file = 'InitialFile.ps', colormode = 'color')
hen = filedialog.asksaveasfilename(defaultextension = '.jpg')
im = Image.open(fev)
print(im)
im.save(hen + '.jpg')
然而,每当我 运行 这个,我得到这个错误:
line 2391, in savefirst
im = Image.open(fev)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 2263, in open
fp = io.BytesIO(fp.read())
AttributeError: 'str' object has no attribute 'read'
显然它无法读取 postscript 文件,因为它 不是 ,据我所知,它本身就是一个图像,因此必须先将其转换为图像,然后再读取作为图像,然后最终转换并保存为 JPEG 文件。 问题是,我如何能够首先将后记文件转换为图像文件在程序内部可能使用Python 成像库? 环顾 SO 和 Google 没有任何帮助,因此非常感谢 SO 用户的任何帮助!
编辑: 遵循 unubuntu's
建议,我的保存功能现在有了这个:
def savefirst():
cnv = getscreen().getcanvas()
global hen
ps = cnv.postscript(colormode = 'color')
hen = filedialog.asksaveasfilename(defaultextension = '.jpg')
im = Image.open(io.BytesIO(ps.encode('utf-8')))
im.save(hen + '.jpg')
然而,现在每当我 运行 那个,我得到这个错误:
line 2395, in savefirst
im.save(hen + '.jpg')
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 1646, in save
self.load()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/EpsImagePlugin.py", line 337, in load
self.im = Ghostscript(self.tile, self.size, self.fp, scale)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/EpsImagePlugin.py", line 143, in Ghostscript
stdout=subprocess.PIPE)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 1544, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'gs'
什么是 'gs'
以及为什么我现在收到此错误?
If you don't supply the file parameter 在对 cnv.postscript
的调用中,然后
a cnv.postscript
returns 作为 (unicode) 字符串的 PostScript。
然后您可以将 unicode 转换为字节并将其提供给 io.BytesIO
并将其提供给 Image.open
。 Image.open
可以接受任何实现 read
、seek
和 tell
方法的 file-like 对象作为其第一个参数。
import io
def savefirst():
cnv = getscreen().getcanvas()
global hen
ps = cnv.postscript(colormode = 'color')
hen = filedialog.asksaveasfilename(defaultextension = '.jpg')
im = Image.open(io.BytesIO(ps.encode('utf-8')))
im.save(hen + '.jpg')
比如大量借鉴A. Rodas' code,
import Tkinter as tk
import subprocess
import os
import io
from PIL import Image
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.line_start = None
self.canvas = tk.Canvas(self, width=300, height=300, bg="white")
self.canvas.bind("<Button-1>", lambda e: self.draw(e.x, e.y))
self.button = tk.Button(self, text="save",
command=self.save)
self.canvas.pack()
self.button.pack(pady=10)
def draw(self, x, y):
if self.line_start:
x_origin, y_origin = self.line_start
self.canvas.create_line(x_origin, y_origin, x, y)
self.line_start = x, y
def save(self):
ps = self.canvas.postscript(colormode='color')
img = Image.open(io.BytesIO(ps.encode('utf-8')))
img.save('/tmp/test.jpg')
app = App()
app.mainloop()
添加到unutbu的答案中,您还可以将数据再次写入BytesIO对象,但是这样做之后您必须寻找到缓冲区的开头。这是一个在浏览器中显示图像的烧瓶示例:
@app.route('/image.png', methods=['GET'])
def image():
"""Return png of current canvas"""
ps = tkapp.canvas.postscript(colormode='color')
out = BytesIO()
Image.open(BytesIO(ps.encode('utf-8'))).save(out, format="PNG")
out.seek(0)
return send_file(out, mimetype='image/png')