Why does the transparency in my image become black, and how do I remove it?

Question:

I am loading a partially-transparent image into pygame and cropping it the following way:

img = pygame.image.load(image_url).convert_alpha()
cropped_img = pygame.Surface((100, 100)).convert_alpha()
cropped_img.blit(img, (0, 0))

The transparent sections of the image are seen as black. set_colorkey((0, 0, 0)) makes the black transparent, but it also makes the black in the image transparent. How would I only get rid of the transparency-caused black?

Asked By: VanquishingSquid

||

Answers:

The line

cropped_img = pygame.Surface((100, 100)).convert_alpha()

does not create a transparent image. pygame.Surface((100, 100)) generates a completely black image. convert_alpha() does not change that. If you create a new surface and use convert_alpha(), the alpha channels are initially set to maximum. The initial value of the pixels is (0, 0, 0, 255)

If you want to crate a transparent image, you have 2 options. Either set a black color key with pygame.Surface.set_colorkey, before converting the foramt of the Surface:

cropped_img = pygame.Surface((100, 100))
cropped_img.set_colorkey(0)
cropped_img = cropped_img.convert_alpha()

or use the SRCALPHA flag to create a Surface with a per pixel alpha format.

cropped_img = pygame.Surface((100, 100), pygame.SRCALPHA)

Final code:

img = pygame.image.load(image_url).convert_alpha()
cropped_img = pygame.Surface((100, 100), pygame.SRCALPHA)
cropped_img.blit(img, (0, 0))
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.