Pillow 和 tkinter 未显示 RGBA 图像

RGBA image not showing up with Pillow and tkinter

我正在尝试使用 Pillow 和 Tkinter 让 PNGA 图像显示在我的 UI 中。我在 macOS 上使用 python 3.7.7。

import sys
import tkinter as tk
from PIL import ImageTk, Image

path = "path_to_image.png"
im = Image.open(path)
print(im.mode) # prints RGBA

root = tk.Tk()

root.title("Karel")

frame = tk.Frame(root)
frame.pack()
canvas = tk.Canvas(frame, bg="white", width=500, height=500)
canvas.pack()
img = Image.open(path)  # PIL solution
img = img.resize((250, 250), Image.ANTIALIAS) #The (250, 250) is (height, width)
img = ImageTk.PhotoImage(img) # convert to PhotoImage
image = canvas.create_image(150,150, image = img)

root.mainloop()

当我尝试使用没有 alpha 通道的图像时,它起作用了。添加 img = ImageTk.PhotoImage(img.convert("RGB")) 以删除 alpha 通道会出现黑框。

如有任何帮助,我们将不胜感激。

图片:

我不明白你想做什么,但问题是你图像中的所有信息都在 alpha(即透明度)通道中。我可以通过在终端中使用 ImageMagick 拆分 R、G、B 和 A 通道来证明这一点,并将它们并排放置:

magick image.png -channel RGBA -separate -background none +smush 10  result.png

所以,红色、绿色和蓝色通道都是零(即黑色),alpha 通道在透明的地方有白色,你可以看到 RGB 黑色,在透明的地方有黑色.

所以,关于你的问题,由于所有信息都在 alpha 通道中,你可以只将 alpha 通道作为你的图像:

#!/usr/bin/env python3

import tkinter as tk
from PIL import ImageTk, Image

root = tk.Tk()

root.title("Karel")

frame = tk.Frame(root)
frame.pack()
canvas = tk.Canvas(frame, bg="red", width=500, height=500)
canvas.pack()
path = "image.png"
img = Image.open(path).getchannel('A')   # Take just alpha channel
img = img.point(lambda a: 255-a)         # Invert black/white
img = img.resize((250, 250), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
image = canvas.create_image(150,150, image = img)

root.mainloop()


请注意,您可以使用 homebrew:

在 macOS 上轻松安装 ImageMagick
brew install imagemagick

如果您使用图像,当您在那里时,也获取这些包:

brew install pngcheck exiftool jhead