How to Convert the Background Color of Image to Match the Color of Pygame Window

How to convert the background color of image to match the color of Pygame window?

You don't need to change the background color of the image to the background color of the window, but make the background of the image transparent.


Set the transparent colorkey by pygame.Surface.set_colorkey:

Set the current color key for the Surface. When blitting this Surface onto a destination, any pixels that have the same color as the colorkey will be transparent.

Note, all the background has to have exactly the same color. In your case the background color seems to be gray (230, 230, 230):

self.image = pygame.image.load('images/ship.bmp').convert()
self.image.set_colorkey((230, 230, 230))

Another option wound be to create a new image (you need to draw it in a painting application) with per pixel alpha (e.g. PNG) and a transparent background:

Sample Image

self.image = pygame.image.load('images/ship.png').convert_alpha()

pygame image background does not match main background

If the background has a uniform color, then you can set the transparent colorkey by pygame.Surface.set_colorkey. For instance if the background is the white (255, 255, 255):

image = pygame.image.load('./car1.bmp').convert()
image.set_colorkey((255, 255, 255))

Anyway that won't solve the issue if the background has multiple colors.

I recommend to use an image format which supports per pixel alpha. For instance PNG (Portable Network Graphics):

image = pygame.image.load('./car1.png').convert_alpha()


See also How can I make an Image with a transparent Backround in Pygame?




Related Topics



Leave a reply



Submit