使用Pillow中的调色板模式GIF保持透明度

时间:2015-10-01 00:05:41

标签: transparency python-imaging-library gif pillow palette

我正在尝试使用包含一个透明度索引的调色板来使用GIF,并使用Pillow创建裁剪的子图像。但是,使用crop()方法时,结果不再透明。

original = Image.open("filename.gif")
print(original.mode) # prints "P", as it should
transparent = original.info["transparency"]
print(transparent) # prints the correct index of the transparent color
cropped = original.crop((0, 0, 10, 10))
print(cropped.info) # transparency no longer present
cropped.info["transparency"] = 255
print(cropped.info) # key is entered, but not transparent in a drawn image

如何通过Pillow中的操作维护或恢复透明索引?如上所示,即使我"暴力"将透明度索引添加回" info"字典,显然不是Python在寻找指定索引的地方。文档还提到像crop()这样的某些方法是懒惰的,并且不传输所有图像信息,那么有没有办法将这些信息重新添加到Image对象?文档建议我可以通过保存新的GIF文件来实现,但在程序运行完成并显示后,我不需要子图像。

编辑以添加以下附加信息:

the original image 原始图像,在GIMP中制作(圆圈为红色,使用IrfanView标记为透明色)

code output 我的代码的输出,圆圈恢复为可见的红色

我的整个节目都在这里:

from tkinter import *
from tkinter import ttk
from PIL import Image
from PIL import ImageTk

class Main:
    def __init__(self):
        self.root = Tk()
        self.background = Canvas(self.root)
        self.background.grid(column=0,row=0)
        self.Draw()

    def Draw(self):
        original = Image.open("Transparency_test.gif")
        print(original.mode) # prints "P", as it should
        transparent = original.info["transparency"]
        print(transparent) # prints the correct index of the transparent color
        cropped = original.crop((0, 0, 50, 50))
        print(cropped.info) # transparency no longer present

        test_uncropped = ImageTk.PhotoImage(image=original)
        test_cropped = ImageTk.PhotoImage(image=cropped)

        self.background.create_image((0,0), image=test_uncropped, anchor=NW)
        self.background.create_image((100,0), image=test_cropped, anchor=NW)

        self.root.mainloop()

instance = Main()

1 个答案:

答案 0 :(得分:1)

我不确定这是最有效的解决方案,但我通过制作图像的大小调整副本,然后将原始图像上的像素粘贴在其上来实现它。我认为结果是你所期望的。

    cropped = original.crop((0, 0, 50, 50))
    cropped.load()
    print(cropped.info) # transparency no longer present

    copied = original.resize((50,50))
    copied.paste(original, (0, 0))
    print(copied.info) # transparency present

    test_uncropped = ImageTk.PhotoImage(image=original)
    test_cropped = ImageTk.PhotoImage(image=cropped)
    test_copied = ImageTk.PhotoImage(image=copied)

    self.background.create_image((0,0), image=test_uncropped, anchor=NW)
    self.background.create_image((100,0), image=test_cropped, anchor=NW)
    self.background.create_image((200,0), image=test_copied, anchor=NW)