Python Forum

Full Version: display error, png with transparent background
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear community,

I display a paddle and a ball in a breakout game.

I've got an error concerning the display of the paddle.

Both pictures (ball + paddle) have got a transparent background.

The ball is displayed correctely - the paddle not (it has a white rectangle as background).

Online I read that I have to you use "convert_alpha()" to display pictures with a transparent background...

I attached ball.png and paddle.png.
In addition to that I attached the wrong display.

Would you please have a look at these files and perhaps tell me what's wrong with paddle.png?
def create_image(file, color=None):
    """
    Create image from a file.  If color is specified, replace all FOREGROUND
    pixels with color pixels.  Modify image so TRANSPARENT colored pixels are
    transparent.
    """
    if color:
        # Recolor the image
        image = Image.open(file).convert("RGB")
        for xy in product(range(image.width), range(image.height)):
            if image.getpixel(xy) == FOREGROUND:
                image.putpixel(xy, color)
        image = pygame.image.fromstring(image.tobytes(), image.size, "RGB")
    else:
        image = pygame.image.load(file)
    image.set_colorkey(TRANSPARENT)
    return image.convert_alpha()
This works as expected on my system. Will you please post enough code to produce the problem?
import pygame
pygame.init ()
SCREEN = pygame.display.set_mode ((300, 100))
TRANSPARENT = (0, 0, 0)

def create_image(file, color=None):
	"""
	Create image from a file.  If color is specified, replace all FOREGROUND
	pixels with color pixels.  Modify image so TRANSPARENT colored pixels are
	transparent.
	"""
	if color:
		# Recolor the image
		image = Image.open(file).convert("RGB")
		for xy in product(range(image.width), range(image.height)):
			if image.getpixel(xy) == FOREGROUND:
				image.putpixel(xy, color)
		image = pygame.image.fromstring(image.tobytes(), image.size, "RGB")
	else:
		image = pygame.image.load(file)
	image.set_colorkey(TRANSPARENT)
	return image.convert_alpha()

paddle = create_image ('paddle.png')
while True :
	for event in pygame.event.get () :
		if event.type == pygame.QUIT :
			pygame.quit ()
			quit ()

	SCREEN.fill ((0, 0, 0))
	SCREEN.blit (paddle, (70, 40))
	pygame.display.update ()
Works fine for me too. I modified my create_image to match, loaded you paddle image and no problems. When you make the paddle image are you passing a color argument? The color should be None. If color is not None the image is converted to RGB (not RGBA) and it replaces FOREGROUND colored pixels with color. Even if there are no matches the conversion to RGBA removes the transparent background.
Dear community,
thanks a lot for your effort!!
I don't need help concerning the transparent background problem anymore.
Many thanks again...