If you haven't taken calculus, you aren't allowed to argue about the value of 00

## Python Imaging Library (PIL) Pixel Editing Crash Course

Post by: Blake
Posted on: 10 Cado 7:2 - 0.71.85
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.

## 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...

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...

image.save(filepath)

And that's all you ever really need!