Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>EDIT: Sorry, my initial answer was only related to transparency within in PyGame, not for saving images.</p> <p>To do pixel modification, you would probably want to use another library such as PIL (Python Imaging Library).</p> <p>See this thread if you want to give PIL a shot: <a href="https://stackoverflow.com/questions/1616767/pil-best-way-to-replace-color">PIL Best Way To Replace Color?</a></p> <p>If you want to stick with PyGame for this, then you should look into pygame.surfarray: <a href="http://www.pygame.org/docs/tut/surfarray/SurfarrayIntro.html" rel="nofollow noreferrer">http://www.pygame.org/docs/tut/surfarray/SurfarrayIntro.html</a></p> <p>EDIT2: Here's a quick snippet:</p> <pre><code>import pygame # initialize pygame pygame.init() pygame.display.set_mode((500, 500)) # load image image_surf = pygame.image.load('test.png',).convert_alpha() # load pixel information from surface image_pixels = pygame.surfarray.pixels3d(image_surf) # create a copy for pixel manipulation new_surf = image_surf.copy() # loop through every pixel i = 0 for x in range(len(image_pixels)): for y in range(len(image_pixels[0])): if image_pixels[x][y][0] == 0 and image_pixels[x][y][1] == 0 and image_pixels[x][y][2] == 0: # set transparency new_surf.set_at((x, y), pygame.Color(0, 0, 0, 0)) # save image pygame.image.save(new_surf, "out.png") </code></pre> <hr> <p>OLD ANSWER: How to achieve transparency within in PyGame</p> <p>You need to look-up set_colorkey(): <a href="http://www.pygame.org/docs/ref/surface.html#pygame.Surface.set_colorkey" rel="nofollow noreferrer">http://www.pygame.org/docs/ref/surface.html#pygame.Surface.set_colorkey</a></p> <p>If your image is already transparent, then you'd just need to load the image with .convert_alpha():</p> <pre><code>asurf = pygame.image.load(os.path.join("shot.png")).convert_alpha() </code></pre> <p>Even if you do not have transparency in your image, it's always a good idea to call .convert():</p> <pre><code>asurf = pygame.image.load(os.path.join("shot.png")).convert() </code></pre> <p>See this: (Link removed due to a 2-links-only limit)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload