如果不是 RGB,则 TKinter 无法显示大型 PNG 图像



我有一些 Tkinter 代码,可以在画布中间显示图像:

class MyClass():
def __init__(self):
self.root = tk.Tk()
width=1280
height=720
self.testImage = Image.open("Drawing.png")
self.canvas = tk.Canvas(self.root,height=height,width=width,bg='blue')
# from some SO post
basewidth=720
wpercent = (basewidth/float(self.testImage.size[0]))
hsize = int((float(self.testImage.size[1])*float(wpercent)))
self.testImage = self.testImage.resize((400,400),PIL.Image.ANTIALIAS)
self.photo = ImageTk.PhotoImage(self.testImage)
self.canvas.create_image(width/2,height/2,image=self.photo)
self.canvas.pack(side="top", fill="both", expand=True)

这会在蓝色 1280x720 画布的中间显示我的图像。如果我将调整大小更改为:

self.testImage = self.testImage.resize((500,500),PIL.Image.ANTIALIAS)

我得到一张空的蓝色 1280x720 画布。我正在努力使图像缩放以填充画布,但是如果我的图像大小超过 400x400,它就会消失。我的基本图像文件是 3000x2000 左右的 PNG。

:您使用Canvas widht/height进行create_image(...,请尝试以下操作:

def __init__(self):
self.root = tk.Tk()
width=1280; height=720
self.canvas = tk.Canvas(self.root,height=height,width=width,bg='blue')
self.testImage = Image.open("Drawing.png")
self.testImage = self.testImage.resize((width,height),PIL.Image.BILINEAR)
width,height=self.testImage.size
self.photo = ImageTk.PhotoImage(self.testImage)
self.canvas.create_image(width/2,height/2,image=self.photo)
self.canvas.pack(side="top", fill="both", expand=True)

考虑这个例子:查看大图像与滚动条-使用-python-tk-and-pil/


评论:...使用双线性我可以扩展...在消失之前高达 800x720

考虑在脚本外部将图像down sample1280x720,而不是在脚本内部down sizeing


根据枕头文档,不支持筛选器PIL.Image.ANTIALIAS

Image.resize(size, resample=0)

返回此图像的调整大小副本。
参数:

size – 请求的大小(以像素为单位(,作为 2 元组:(宽度、高度(。
重采样 – 可选的重采样滤波器。
这可以是太平船务之一。图片.最近,PIL。图片框,PIL。图片.双线性,PIL.图片.哈明,PIL.图像.BICUBIC 或 PIL。图片.兰佐斯.
如果省略,或者图像具有模式"1"或"P",则将其设置为 PIL。图片.最近。
请参阅:过滤器。

我设法使用此处找到的解决方案解决了这个问题。

只需更改:
self.testImage = Image.open("Drawing.png")

self.testImage = Image.open("Drawing.png").convert("RGB")
允许它按预期运行。

最新更新