我正在使用 Tkinter 在 Python 中开发 GUI 来学习图像处理。GUI 的流程是这样的
加载图像 (jpg|png|...) => 调整大小/缩略图 (240 * 240) => 预览图像
from Tkinter import *
import PIL
class Window:
def __init__(self, master):
master.title("Image Processing test")
master.minsize(800, 400)
from PIL import Image
im = Image.open("IMG_0562.png")
size = 240, 240
im.thumbnail(size)
p = im.tobytes()
# photo = PhotoImage(file="IMG_0562.gif")
# photo = BitmapImage(data=p)
w = Label(root, image=photo, width=240, height=240).grid(row=20, column=2)
self.photo = photo
root = Tk()
window = Window(root)
root.mainloop()
我的问题是我无法以正确的格式获取图像以在Label
. 由于Label
只接受PhotoImage
和BitmapImage
。PhotoImage
不支持png
或jpg
归档。所以我使用Image
fromPIL
来加载和调整我的彩色图像。我也试过Image.tobitmap()
,Image.tobytes()
但在这种情况下没有用。
通过使用将图像保存在内存中解决了问题 io.BytesIO()
from Tkinter import *
from PIL import Image
import io
class Window:
def __init__(self, master):
master.title("Image Processing test")
master.minsize(800, 400)
im = Image.open("IMG_0562.png")
size = 240, 240
im.thumbnail(size)
b = io.BytesIO()
im.save(b, 'gif')
p = b.getvalue()
photo = BitmapImage(data=p)
w = Label(root, image=photo, width=240, height=240).grid(row=20, column=2)
self.photo = photo
root = Tk()
window = Window(root)
root.mainloop()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句