[Tutor] Snakes and Ladders (is: PNG transparency)
jnewton at fuelindustries.com
Fri Jan 4 21:15:10 CET 2008
Hello again Python Programmers!
To reply to my own question:
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
I've modified the code at...
... 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() is non-zero.
However, the pygame documentation at...
... 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,
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
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()
# (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()
# 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))
More information about the Tutor