Reputation: 43
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?
Upvotes: 3
Views: 778
Reputation: 210878
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))
Upvotes: 2