Pil Transparency

John Michelsen john.michelsen at gte.net
Sat May 22 17:53:18 EDT 1999


Hi all,

I was wondering if anyone knows how to save an image in PIL
with transparency.  Say changing all of the black pixels of an image
to be transparent in gif, png format.  The documentation had a few
references to pasting with transparency masks, but not enough
that I could find to figure it out.  Here's what I came up with:



from Tkinter import *
import Image, ImageTk
import tkFileDialog

class Transparency:
    def __init__(self, parent):
        self.canvas = Canvas(parent, bg='white')
        self.canvas.pack()
        b = Button(parent, command=self.open, text="Open")
        b.pack()

    def open(self):
        self.canvas.delete(ALL)
        filename = tkFileDialog.askopenfilename()
        if filename != '':
            im = Image.open(filename)
            # use black as transparent
            mask = im.point(lambda i: i == 0)  #gives a bad mask.
            region = im.crop()
            im.paste(region, None, mask)

            self.graphic = ImageTk.PhotoImage(image=im)
            self.canvas.create_image(100, 100, image=self.graphic)


if __name__ == "__main__":
    root = Tk()
    test = Transparency(root)
    root.mainloop()


Thanks,

John






More information about the Python-list mailing list