DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Using Transparent Gif/png With Image's Blitting

  • submit to reddit
        pys60's Image class will load a transparent gif/png
just like a non-transparent one.
But its blit() method accept a mask paramenter.
I have talked about this in a <a href=>previous snippet</a>.

The missing link is to create a mask automatically
from the Image. It's typically the top-left pixel.
You can use Image's getpixel() which is undocumented.
I show typical use of getpixel <a href=>here</a>.

Combine them all, here's the automask function.
def automask(im):
    width, height = im.size
    mask =, '1') # black and white
    tran = im.getpixel((0,0))[0]   # transparent top-left
    for y in range(height):
        line = im.getpixel([(x, y) for x in range(width)])
        for x in range(width):
            if line[x] == tran:
                mask.point((x,y), 0)  # mask on the point
    return mask
An example usage
from graphics import Image

ship ='E:\\Images\\ship.gif')
mask = automask(ship)

canvas.blit(ship, mask=mask)  # don't forget to create canvas first
A Sprite class can be defined based on this too.