[Tutor] Snakes and Ladders (is: PNG transparency)

James Newton jnewton at fuelindustries.com
Fri Jan 4 21:15:10 CET 2008


Hello again Python Programmers!

To reply to my own question:

-----Original Message-----
I'm importing a graphic named Counter_1.png for the counter.  I'd like
its background to be transparent, using the PNG's built-in alpha
channel.
--------------------------

I've modified the code at...
<http://rene.f0o.com/mywiki/LectureFour#head-52d34285fd010fdc1164ea8ccbe
77980cac42b61>
... so that it uses pygame's image.convert_alpha() if the loaded image
appears to have an alpha channel (see below).  My code does this by
checking if image.get_masks()[3] is non-zero.

However, the pygame documentation at...
  <http://www.pygame.org/docs/ref/surface.html#Surface.get_masks>
... states that .get_masks() is "not needed for normal Pygame usage".
This suggests to me that I am missing a more standard way of detecting
if an pygame.image has an alpha channel.

Is my technique likely to fail?  Is there a better way of doing this?

Thanks in advance for your insights,

James




def load_image(filename, colorkey=None):
    # INPUT: <filename> should be an absolute or relative path to an
    #         image file
    #        <colorkey> should be None, an rgb tuple, or -1, in which
    #         case the color of the top left pixel will be used.
    # ACTION: Attempts to read in an image from filename, and (if
    #         required) applies a transparency mask to it.
    # OUTPUT: Returns a pygame Surface   
    
    try:
        image = pygame.image.load(filename)
    except pygame.error, message:
        print "Cannot load image:", filename
        raise SystemExit, message
    
    # Make a new copy of a Surface and convert it to screen depth
    vAlpha = image.get_masks()[3]
    # (255, 65280, 16711680, -16777216) for an RGBA image
    # (31744, 992, 31, 0) for a 2-bit/pixel rrrrrgggggbbbbbx BMP image

    if vAlpha != 0:
        # The image has an alpha channel
        image = image.convert_alpha()
    else:
        # The image has no alpha channel, but we may have a colorkey
        image = image.convert()
    
        if colorkey is not None:
            if colorkey is -1:
                colorkey = image.get_at((0, 0))
            image.set_colorkey(colorkey, RLEACCEL)

    return image




More information about the Tutor mailing list