Search code examples
pythontransparency

pygame.display.set_icon() not handling transparency too well


Yes, I know that there is another post asking this, but I tried the answer in that, and it didn't work, it just made it worse. Here are all the posts I've tried:

PyGame: Applying transparency to an image with alpha?

Pygame.display.set_icon unable to show transparecy

How do I set a transparent icon?

And my result from trying to use transparency was WAY different than them. Here's my code:

import pygame

pygame.init()

screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Undertale")
pygame.display.set_icon(pygame.image.load("icon.png").convert_alpha())

and here is the result:

enter image description here

Here is the original image:

enter image description here

Any help?

EDIT: I did what @user2588654 said:

Given the above, my suggestion would be to try remaking the heart at 32x32 pixels with a white background without transparency and apply the colorkey. Let me know if this helps!

And here is my code:

import pygame

pygame.init()

screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Undertale")
icon = pygame.image.load("icon.png")
icon.set_colorkey((0,255,0))
pygame.display.set_icon(icon)

Here is the new icon.png:

enter image description here

And here is the result:

enter image description here

Although it isn't much, It's still a little annoying. If it's not possible to fix, that's fine, and if it is, then I'd like to know it.


Solution

  • Your code is fine. When I ran it with your test heart image, I got the following test warning in my command prompt: libpng warning: iCCP: known incorrect sRGB profile. Following the advice here, I converted it using image magick and that got rid of the error, but it still looked like your screenshot, so this is probably not too important.

    According to the pygame documentation on this here for pygame.display.set_icon(), it looks like most systems want a smaller image around 32x32 pixels. Resizing your image to that size removed most of the artifacts on the image, but this is not ideal since your heart is pixel art around 20x20 pixels. Furthermore, it looks like icons in pygame do not support complete transparency, but instead only support colorkey. That is, you basically choose a color to set as completely transparent by calling surf.set_colorkey((255, 255, 255)), where surf refers to your icon image surface after pygame.image.load("icon.png").convert_alpha(). In my example, the tuple (255, 255, 255) refers to a white color.

    Given the above, my suggestion would be to try remaking the heart at 32x32 pixels with a white background without transparency and apply the colorkey. Let me know if this helps!