我正在尝试通过使用io.BytesIO()
将图像保存在内存中来在tkinter中显示缩略图。我得到_tkinter.TclError: format error in bitmap data
。 BitmapImage
supports X11位图图像。所以我的问题是如何在将图像传递到xbm
方法之前将其转换为BitmapImage
?
from PIL import Image, ImageTk
import tkinter.scrolledtext as tkst
import tkinter as tk
import os, os.path
import io
class Example(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
img = Image.open("1.jpg")
image_size = 256, 256
img.thumbnail(image_size,Image.ANTIALIAS)
b = io.BytesIO()
img.save(b, 'gif')
p = b.getvalue()
photo = tk.BitmapImage(data=p)
self.photo = photo
self.imageview = tk.Label(self, image = self.photo, background="black")
self.imageview.grid(row=0, column=0, rowspan=2, sticky="nsew")
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.geometry("800x400")
root.mainloop()
上次,我使用此代码解决了问题,但有时图像的高度会被切除。
image = Image.open("1.jpg")
basewidth = 900
wpercent = (basewidth/float(image.size[0]))
hsize = int((float(image.size[1])*float(wpercent)))
image = image.resize((basewidth,hsize),Image.ANTIALIAS)
self.photo = ImageTk.PhotoImage(image)
self.imageview.configure(image=self.photo)