Search code examples
pythonimagepygamepngalpha

saving an image with a transparent background


i've got some issues with my program:

minimap = pygame.Surface((100, 100))
background = pygame.Surface((minimap.get_width(), minimap.get_height()))
background.fill((0, 0, 0))
background.set_alpha(0)
minimap.blit(background, (0, 0, minimap.get_width(), minimap.get_height()))
pygame.image.save(minimap, "minimap.png")

the thing is, I want the background to be transparent because I display it on something else later on and i want to see behind it, so I've used another surface where I've set a color and put the alpha to 0, after that the background is set to minimap.

If you have any clue please let me know


Solution

  • background doesn't have a per pixel alpha format. Set the SRCALPHA flag to create a surface with an image format that includes a per-pixel alpha. Don't fill the background with an opaque black color:

    background = pygame.Surface((minimap.get_width(), minimap.get_height()))
    background.fill((0, 0, 0))
    background.set_alpha(0)

    background = pygame.Surface(minimap.get_size(), pygame.SRCALPHA)
    

    Alternatively you can set a transparent color key with set_colorkey()

    background = pygame.Surface((minimap.get_width(), minimap.get_height()))
    background.set_colorkey((0, 0, 0))