Using transparent gif/png with Image's blitting
just like a non-transparent one.
But its blit() method accept a mask paramenter.
I have talked about this in a previous snippet.
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 here.
Combine them all, here's the automask function.
1 2 def automask(im): 3 width, height = im.size 4 mask = Image.new(im.size, '1') # black and white 5 tran = im.getpixel((0,0))[0] # transparent top-left 6 for y in range(height): 7 line = im.getpixel([(x, y) for x in range(width)]) 8 for x in range(width): 9 if line[x] == tran: 10 mask.point((x,y), 0) # mask on the point 11 return mask
An example usage
1 2 from graphics import Image 3 4 ship = Image.open('E:\\Images\\ship.gif') 5 mask = automask(ship) 6 7 canvas.blit(ship, mask=mask) # don't forget to create canvas first
A Sprite class can be defined based on this too.