I need python to change the color of one individual pixel on a picture, how do I go about that?
            Asked
            
        
        
            Active
            
        
            Viewed 2.9k times
        
    23
            
            
        - 
                    2@akonsu: Judging by his tags he's already found that library... – Matti Virkkunen Aug 29 '10 at 20:20
- 
                    what file format? just bitmap data? – Nate Aug 29 '10 at 20:20
- 
                    The image is PNG format. – rectangletangle Aug 29 '10 at 20:23
- 
                    4read http://stackoverflow.com/questions/138250/read-the-rgb-value-of-a-given-pixel-in-python-programaticly – Gabi Purcaru Aug 29 '10 at 20:30
1 Answers
25
            
            
        To build upon the example given in Gabi Purcaru's link, here's something cobbled together from the PIL docs.
The simplest way to reliably modify a single pixel using PIL would be:
x, y = 10, 25
shade = 20
from PIL import Image
im = Image.open("foo.png")
pix = im.load()
if im.mode == '1':
    value = int(shade >= 127) # Black-and-white (1-bit)
elif im.mode == 'L':
    value = shade # Grayscale (Luminosity)
elif im.mode == 'RGB':
    value = (shade, shade, shade)
elif im.mode == 'RGBA':
    value = (shade, shade, shade, 255)
elif im.mode == 'P':
    raise NotImplementedError("TODO: Look up nearest color in palette")
else:
    raise ValueError("Unexpected mode for PNG image: %s" % im.mode)
pix[x, y] = value 
im.save("foo_new.png")
That will work in PIL 1.1.6 and up. If you have the bad luck of having to support an older version, you can sacrifice performance and replace pix[x, y] = value with im.putpixel((x, y), value).
 
     
    