segunda-feira, 12 de janeiro de 2009

PyS60: Creating masks for images

Masks are used to create transparency aspect to images. Supose you have an image with dark background color. You can create a mask and attach it to the original image and them set your background color to be transparent.

First you need to open the image:
myImage = graphics.Image.open("C:\\image.png")
Then:
#get with and weight of the image
width, height = myImage.size

#now, create the mask, mode 1 means that the image will be created in black and white mode
mask = Image.new(size=myImage.size, mode='1')

#get the first pixel of the image, wich is located at the background area
tran = myImage.getpixel((0,0))[0]

#make the transformation
for y in range(height):
line = myImage.getpixel([(x, y) for x in range(width)])

for x in range(width):
if line[x] == tran:
mask.point((x,y), 0)

Now you have a masked version of the image pointed by mask variable. To use the mask just draw the original image in the body canvas:

background.blit(myImage,(x,y),(z,w), mask = mask)

Where background variable is the reference to your background. Parameters:

1. The original image
2. A tuple defining the size of the image (just if yout want to resize the original image to fit your screen)
3. Is the position you want to draw the image in the screen.

The last one is the mask reference.

Links and code examples can be found in the Python Wiki at Forum Nokia