I'm updating a class that loads and displays an image - an Image class.  The 
class also has many additional calls to rotate, scale, show, hide, etc.  I'm 
using pygame 1.9.6 with Python 3.7.3

I know that I should be converting the original image that is loaded into a 
better format for displaying in a window. So I want to change my code to take 
care of that conversion.  My understanding is that if the image has an alpha 
channel, then when I load the image I should use ".convert_alpha()", and if 
not, I should use ".convert()".  (Please let me know if this is not correct.)

I want people who use this class to be able to load any image (typically png or 
jpg file), and have my code do the conversion the appropriate way without 
having to ask the caller to let me know the type of the image.

Therefore, in my class, when I load an image, I want to know if the image has 
an alpha channel.  I'm not sure of the best way of doing this.  So far, I've 
come up with two different ways to do this. 

Approach #1 - check the extension of the file:
self.originalImage = pygame.image.load(path)
if path.endswith('.png'):
    self.originalImage.convert_alpha()
else:
    self.originalImage.convert()

Approach #2 - check the bitdepth of the image:
self.originalImage = pygame.image.load(path)
if pygame.Surface.get_bitsize(self.origialImage) == 24:
    self.originalImage.convert_alpha()
else:
    self.originalImage.convert()

In my tests, both seem to work, but I don't feel completely comfortable with 
either one.  I know very little about art - for example, I don't know if all 
".png" files have an alpha channel.  I'm also not sure if all images with an 
alpha channel are 24 bits deep.
Looking to see if either of these is better than the other, or if there is a 
different approach that I should take.  Open to suggestions.
Thanks in advance,
Irv

Reply via email to