支持缩放和更改透明度的 PNG 图像 python

PNG image that support scaling and changing transparency in python

我想在 canvas 上显示 PNG 图片。 在此之前,我需要调整它的大小并更改透明度。

我发现我可以像这样使用 PhotoImage 加载图像和更改 alpha 通道:

image1 = PIL.Image.open('aqua.png')
image1.putalpha(128)
gif1 = ImageTk.PhotoImage(image1)

我也可以加载 PhotoImage 并像这样调整它的大小:

gif1 = PhotoImage(file = 'aqua.png')
gif1 = gif1.subsample(5)

但我不能在同一个 PhotoImage

上执行这两个操作

我明白 PhotoImageImageTk.PhotoImage 在我的代码中是不同的 类。

>> print (ImageTk.PhotoImage)
<class 'PIL.ImageTk.PhotoImage'>
>> print (PhotoImage)
<class 'tkinter.PhotoImage'>

我试图在两者中找到我需要的功能 类 但没有成功。

也许我需要执行 subsample 然后将我的 tkinter.PhotoImage 转换为 PIL.ImageTk.PhotoImage 然后执行 putalpha 但这听起来很奇怪。

请在 Python 中向我介绍有关 png 烹饪的正确方向。

这是我的全部代码:

from tkinter import *
import PIL
from PIL import Image, ImageTk

canvas = Canvas(width = 200, height = 200)
canvas.pack(expand = YES, fill = BOTH)

image1 = PIL.Image.open('aqua.png')
image1.putalpha(128)
gif1 = ImageTk.PhotoImage(image1)

# gif1 = PhotoImage(file = 'aqua.png')
# next line will not work in my case
gif1 = gif1.subsample(5)

canvas.create_image(0, 0, image = gif1, anchor = NW)
mainloop()

您可以使用 Image class 中包含的 resize 方法。这是修改后的代码:

from tkinter import *
from PIL import Image, ImageTk

canvas = Canvas(width = 200, height = 200)
canvas.pack(expand = YES, fill = BOTH)

image1 = Image.open('aqua.png')
image1.putalpha(128)
image1 = image1.resize((image1.width//5,image1.height//5))
gif1 = ImageTk.PhotoImage(image1)

canvas.create_image(0, 0, image = gif1, anchor = NW)
mainloop()