Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Using transparent gif/png with Image's blitting

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 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.
def automask(im):
    width, height = im.size
    mask = Image.new(im.size, '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 = Image.open('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.

Image/canvas bliting

I can't remember how to call the blit method.
So, here's just a personal reminder.
(BTW, the pys60 doc has a wrong order between target and source)
app.body = c = Canvas()
w,h = 20,20
im = Image.new(size=(w,h))

# here's prototype
# blit(im, source=(0,0,w,h), target=(0,0), mask=None, scale=0)
# here are examples
c.blit(im)  # put entire image on top-left
c.blit(im, target=(70,70)) # put it about mid-screen
c.blit(im, (0,0,w/2,h/2))  # put a quater image on top-left

# double the image size and put it about mid-screen
c.blit(im, target=(60,60,100,100), scale=1)

If scale is not specified and source <> target, the image
will be clipped instead of resized.

mask is a 1-bit image with the same size as image.
mask = Image.new((w,h),'1')

Pixel on the image will be copied if the same pixel
on the mask is 'white'.
So we can use mask to make 'Sprite'.
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS