Pil Transparency
John Michelsen
john.michelsen at gte.net
Sun May 23 14:33:19 EDT 1999
>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:
Figured it out with a bunch of trial and error.
Could put something like this in the documentation to
save the next person. :^)
John
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)
if im.mode != "RGBA":
im = Image.open(filename).convert("RGBA")
source = im.split()
R, G, B, A = 0, 1, 2, 3
mask = im.point(lambda i: i > 0 and 255) # use black as transparent
source[A].paste(mask)
im = Image.merge(im.mode, source) # build a new multiband image
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()
More information about the Python-list
mailing list