Hein de Wilde
Hein de Wilde

Reputation: 197

Make the background of an image transparent in Pygame with convert_alpha

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

Here is (the relevant part of) my code:

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

What am I doing wrong? Thanks in advance!

Upvotes: 2

Views: 12711

Answers (1)

Ted Klein Bergman
Ted Klein Bergman

Reputation: 9746

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, the bmp format do not have native transparency support.

If it does contain alpha you should be able to use the method convert_alpha() to return a Surface with per-pixel alpha. You don't need to pass anything to this method; if no arguments are given the new surface will be optimized for blitting to the current display.

Here's an example code demonstrating this:

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()

And my image ("temp.png"):

enter image description here

If it doesn't contain alpha there are two easy fixes.

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

Upvotes: 9

Related Questions