Make the background of an image transparant in Pygame with convert_alpha
<p>I am trying to make the background of an image transparant in a Pygame script. Now the background in my game is black, instead of transparant. I read somewhere else that I could use <code>convert_alpha</code>, but it doesn't seem to work.</p>

<p>Here is (the relevant part of) my code:</p>

<pre><code>import PIL
gameDisplay = pygame.display.set_mode((display_width, display_height))
img = pygame.image.load('snakehead1.bmp').convert_alpha(gameDisplay)
</code></pre>

<p>What am I doing wrong? Thanks in advance!</p>

<p>To make an image transparent you first need an image with alpha values. Be sure that it meets this criteria! I noticed that my images doesn't save the alpha values when saving as bmp. Apparently, <a href="http://www.ehow.com/how_12224322_make-bmp-transparent.html" rel="nofollow">the bmp format do not have native transparency support</a>.</p>

<p><strong>If it does contain alpha</strong> you should be able to use the method <code>convert_alpha()</code> to return a Surface with per-pixel alpha. You don't need to pass anything to this method; if no arguments are given <a href="http://www.pygame.org/docs/ref/surface.html#pygame.Surface.convert_alpha" rel="nofollow">the new surface will be optimized for blitting to the current display</a>.</p>

<p>Here's an example code demonstrating this:</p>

<pre><code>import pygame
pygame.init()

screen = pygame.display.set_mode((100, 100))
image = pygame.image.load("temp.png").convert_alpha()

while True:
    screen.fill((255, 255, 255))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()

    screen.blit(image, (0, 0))
    pygame.display.update()
</code></pre>

<p>And my image (<em>"temp.png"</em>): </p>

<p><a href="http://i.stack.imgur.com/WVlsf.png" rel="nofollow"><img src="http://i.stack.imgur.com/WVlsf.png" alt="enter image description here"></a></p>

<p><strong>If it doesn't contain alpha</strong> there are two easy fixes.</p>

<ol>
<li>Save the image with a different file format, like png.</li>
<li>Use colorkeys. This works if you only need to remove the background. It is as easy as putting the line of code <code>image.set_colorkey((0, 0, 0))</code>, which will make all black colors transparent.</li>
</ol>

<p>You can read more about pygame Surfaces and transparency at <a class='doc-link' href="http://stackoverflow.com/documentation/pygame/7079/drawing-on-the-screen/23788/transparency#t=201610082359454420873">Stack overflows pygame documentation</a>.</p>

python pygame