【问题标题】:PNG image that support scaling and changing transparency in python在 python 中支持缩放和更改透明度的 PNG 图像
【发布时间】:2018-10-01 18:31:45
【问题描述】:

我想在画布上显示 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()

【问题讨论】:

    标签: python-3.x tkinter python-imaging-library transparency resizable


    【解决方案1】:

    您可以使用Image 类中包含的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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-21
      • 2011-06-08
      • 1970-01-01
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多