1

I am already struggling with this issue for quite some time, because I would like to keep the transparant background of a png image when using it in Python and pygame. If I use the code below, the transparant background becomes black. A screenshot is shown below. Note that I would like to be able to modify the colors of the image after loading, that's why I use the image.putpixel function.

import pygame
from PIL import Image

def pilImageToSurface(pilImage):  
    return pygame.image.fromstring(pilImage.tobytes(), pilImage.size, pilImage.mode).convert()

image = Image.open('creature1.png')
image.putpixel((10,10), (256,0,0))

pygame.init()
screen = pygame.display.set_mode([100, 100])
screen.fill([10, 100, 10])

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    pygameSurface = pilImageToSurface(image)
    screen.blit(pygameSurface, pygameSurface.get_rect(center = (50,50)))
    pygame.display.flip()
    
pygame.quit()

enter image description here

Margaret
  • 21
  • 2

1 Answers1

1

You have to use convert_alpha() instead of convert():

return pygame.image.fromstring(pilImage.tobytes(), pilImage.size, pilImage.mode).convert()

return pygame.image.fromstring(pilImage.tobytes(), pilImage.size, pilImage.mode).convert_alpha()

See pygame.image:

The returned Surface will contain the same color format, colorkey and alpha transparency as the file it came from. You will often want to call convert() with no arguments, to create a copy that will draw more quickly on the screen.
For alpha transparency, like in .png images, use the convert_alpha() method after loading so that the image has per pixel transparency.


Furthermore it is not necessary to use PLI. Use pygame.image.load instead:

pygameSurface = pygame.image.load('creature1.png').convert_alpha()
pygameSurface.set_at((10, 10), (255, 0, 0))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174