[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

RE: [pygame] Question about .bmp files and transparency



-----Original Message-----
From: owner-pygame-users@seul.org [mailto:owner-pygame-users@seul.org]
On Behalf Of SB
Sent: 9. september 2003 15:27
To: pygame-users@seul.org
Subject: Re: [pygame] Question about .bmp files and transparency

In GIMP, use Filters->Colors->Color To Alpha.  Choose black as the
color.  Then save it in a format that respects the alpha, like PNG.

************************************************************************

That was not really the solution I was looking for.... But thanks for
the tip. Just learned how to do that in PaintShop Pro :)


What I did want to do though, was to do this in the program since it
will be MUCH easier to add more images etc. later on. And not having to
turn to a image editing program.

I was thinking I could take the image, load it into a surfarray, add the
rgb channels together into an alpha value, write the 32bit rgba value
back into an array of the same size and then write that array out into a
new surface.

So this is what I've got right now. This code is placed inside a
load_image method, which takes a few extra arguments besides image
path/filename; most important the needalpha flag. 
If needalpha is true it does some pixel computations and at the end
returns a 32bit surface with an active alpha channel.
So any image you load with the needalpha-flag set to true will load onto
the screen with 'alpha blending' based on the luminance value of the RGB
channels.

    surface = surface.convert_alpha()
    if needalpha == 1:
        masks = surface.get_masks()
        shifts = surface.get_shifts()
        pixelarray = surfarray.array2d(surface)
        height = len(pixelarray)
        width = len(pixelarray[0])
        alpha = array(pixelarray)
        for i in range(height):
            for j in range(width):
                pixel = pixelarray[i][j]
                r = (pixel & masks[0]) >> shifts[0]
                g = (pixel & masks[1]) >> shifts[1]
                b = (pixel & masks[2]) >> shifts[2]
                a = r | g | b
                alphapixel = (a << 24) | (r << shifts[0]) | (g <<
shifts[1]) | (b << shifts[2])
                alpha[i][j] = alphapixel
        surfarray.blit_array(surface,alpha)



This works pretty well :)
Actually, I would say extremely well... It's very easy to just create
some image for 2d flares/explosions/smoke effects in a paint program and
not having to worry about saving the right alpha layer/setting the right
transparency color. The darker a pixel is the more transparent it will
get.

Only thing now is to tweak the loop. I had to do it this way for testing
purposes.

Shouldn't matter what image format you use. Except if you use .png or
some other format which supports alpha layers, just load them without
the 


-erlend