Skip to main content
GameDev.net gamedev.net
🔒 Locked

howto: Transparent Image in Python

Started by cassim Jan 23, 2007 at 6:23 AM 0 replies 750+ views
Original Post
cassim
cassim
Hi All, I have saved a thumbnail image with a python program and now wants this image to be transparent so that when it is attached with some other image, the particular background of thumbnails does not show...anyone here knows how to achieve that with the help of PIL? thanks in advance
Euronomus
Euronomus
First I would recommend reading The pil handbook ,
it has a lot of info on the questions you're asking, and if you use pil alot you'll need to refer to it quite a bit.

To answer this specific question, you need to understand image alpha values.
Put simply an alpha value is an integer between 0 and 255, 0 being completely transparent, and 255 being completely opaque.

img.paste takes 3 args, (sourceimage ,position, mask).
The mask is a single-band image, or an image with an alpha band.

Wherever the mask image has a value of 0 the "underneath" pixel will show, wherever it has a value of 255 the "above" pixel will show,
and any value in-between will result in a mixture of both pixels.

if you want an image to hold its own alpha band it needs to be converted to
'RGBA' mode (if its not already) then you can just use an image as its own mask.
eg. image.paste(image2, pos, image2)

Now if all you want to do is remove one color (colorkeying),
I haven't found an "easy" way to do it but you can do something like this:
(not tested)
def getmask(img, color):    data = img.getdata()    mask = Image.new('L', img.size, 255)    mdata = mask.getdata()    for ind, pix in enumerate(data):        if pix == color:             mdata[ind] = 0    mask.putdata(mdata)    return mask

but I imagine this would be quite slow

[Edited by - Euronomus on January 24, 2007 3:12:11 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.