pygame, saving a image with low opacity

Question:

im making some images in my game and sometimes drawing colors with low opacity, but when i try to save it with;

pygame.image.save(the_img, the_name)

it’s saves the image like i painted it with 255 opacity.
so how can i save a .png image that has colors with low opacity. in this image the blue color has 128 opacity (50%) but it’s saves it like the opacity 255?
when i blit this image to my display it’s shows it right but when i download it it’s wrong??

Asked By: Planet Venus

||

Answers:

The image format must be one that supports an alpha channel (e.g. PNG):

pygame.image.save(the_img, "my_image.png")

If you have a Surface with a color key (set_colorkey), you have to change the pixel format of the image including per pixel alphas with pygame.Surface.convert_alpha:

pygame.image.save(the_img.convert_alpha(), the_name)

If you have a surface with a global alpha value (set_alpha), you need to blit the Surface on a transparent Surface (pygame.SRCALPHA) of the same size and store that transparent Surface (this also works for a Surface with a color key):

the_img.set_colorkey((0, 0, 0))
the_img_alpha = pygame.Surface(the_img.get_size(), pygame.SRCALPHA)
the_img_alpha.blit(the_img, (0, 0))

pygame.image.save(the_img_alpha, the_name)

Minimla example:

import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

the_img = pygame.Surface((200, 200))
pygame.draw.circle(the_img, (255, 0, 0), (100, 100), 100)
the_img.set_alpha(127)

the_img.set_colorkey((0, 0, 0))
the_img_alpha = pygame.Surface(the_img.get_size(), pygame.SRCALPHA)
the_img_alpha.blit(the_img, (0, 0))
pygame.image.save(the_img_alpha, "the_img.png")

run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    window_center = window.get_rect().center

    window.fill((127, 127, 127))
    window.blit(the_img, the_img.get_rect(center = window.get_rect().center))
    pygame.display.flip()

pygame.quit()
exit()
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.