Pillow (PIL)
Pillow is a library for working with images in Python. You can open, edit, draw on, and save image files. It’s used in the Generative Art project.
For everything Pillow can do, check out the official Pillow docs .
Installation
pip install pillowImporting
Even though the library is called Pillow, you import it as PIL:
from PIL import Image, ImageDrawPillow is the modern, maintained version of an older library called PIL (Python Imaging Library). The name stuck for the import.
Opening and Saving Images
from PIL import Image
img = Image.open("photo.jpg")
img.save("copy.png")Creating a Blank Image
from PIL import Image
# Image.new(mode, size, color)
img = Image.new("RGB", (500, 500), color=(255, 255, 255)) # white canvas
img.save("canvas.png")"RGB" means the image uses red, green, and blue channels. Colors are tuples of three values from 0–255.
Drawing Shapes
draw.circle() was added in Pillow 10.0.0. If you get an error, upgrade with:
pip install --upgrade pillowfrom PIL import Image, ImageDraw
img = Image.new("RGB", (500, 500), color=(0, 0, 0)) # black background
draw = ImageDraw.Draw(img)
# Rectangle
draw.rectangle([50, 50, 200, 200], fill=(255, 0, 0)) # red square
# Circle
draw.circle([325, 325], radius=75, fill=(0, 100, 255)) # blue circle
# Line
draw.line([0, 0, 500, 500], fill=(255, 255, 0), width=3) # yellow diagonal
img.save("shapes.png")Common Colors
Colors in Pillow are (red, green, blue) tuples, each value 0–255:
| Color | Tuple |
|---|---|
| Red | (255, 0, 0) |
| Green | (0, 255, 0) |
| Blue | (0, 0, 255) |
| White | (255, 255, 255) |
| Black | (0, 0, 0) |
| Yellow | (255, 255, 0) |
| Purple | (128, 0, 128) |
Image Size and Pixels
img = Image.open("photo.jpg")
print(img.size) # (width, height) in pixels, e.g. (1920, 1080)
print(img.mode) # color mode, e.g. "RGB"Summary
Pillow is a powerful library for working with images in Python. You can create new images, draw shapes, and manipulate existing images. It’s a great tool for projects that involve graphics, like the Generative Art project.
For the full documentation, see the Pillow documentation .