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))
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')
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[4, 5] # x = 4, y = 5 (0-indexed, of course)
color = pixels[4, 5] # 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[4, 5] = (128, 0, 128, 255) # purple
To get the width/height of an image...
width = image.size[0]
height = image.size[1]
height = image.size[1]
To save an image to file...
image.save(filepath)