Login | Register
Nerd ParadiseArtisanal tutorials since 1999
I always seem to have trouble finding a reference that just cuts to the chase and tells me how to read and edit arbitrary pixels in an image using PIL. So I guess I'll just throw one together.

A word of caution: I usually don't use PIL for real-time image manipulation. As such, these methods may not be the most performant that PIL has to offer, but they're the most direct and for things like converting a few files in a folder to have a transparent background, or adding watermarks, etc. performance does not matter and this is more than sufficient.

Without further ado:

To get started:

Download the Python Imaging Library if you haven't done so. Once you have that taken care of, add the following import to your code:
import Image

To create an image from a file...

image = Image.open(filepath)

To create an image from scratch...

width = 400
height = 300
Image.new('RGBA', (width, height))

For easy and direct pixel editing...

Images have different palette modes. If the image has a palette, setting arbitrary RGBA values becomes a bit tricky. It's best to just convert it to an RGB or RGBA image...
if image.mode != 'RGBA':
    image = image.convert('RGBA')

Change 'RGBA' to 'RGB' if you don't care about alpha.

To get the color of a pixel...

pixels = image.load()
color = pixels[45# x = 4, y = 5 (0-indexed, of course)

This will return a tuple containing 3 numbers for RGB images and 4 for RGBA images.
For example, this would be non-translucent red: (255, 0, 0, 255)
As the palette mode name implies, the order is R, G, B, A.

To set the color of a pixel...

The pixels array mentioned above is also writable:
pixels[45] = (1280128255# purple

To get the width/height of an image...

width = image.size[0]
height = image.size[1]

To save an image to file...


Hey, there, Python folks. Hope you enjoyed the post. I just wanted to give a quick shout-out for a weekly Python code golf that I recently started up over on StringLabs.io. If you like Python puzzles please come check it out!