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()