Pillow

How to Work with Pillow

Pillow is a powerful and user-friendly Python imaging library, letting you open, edit, create, and save images in many formats. Pillow is the actively maintained fork of the original PIL.

Install it with:

pip install Pillow

Then import it at the top of your Python files.

from PIL import Image

Opening and Viewing Images

You can open .jpg, .png, .gif, .bmp, .tiff, and more.

img = Image.open('image.jpg')  # Open an image file
img.show()                     # Opens the image in the default viewer

Getting Image Info

print(img.format)      # JPEG, PNG, etc.
print(img.size)        # (width, height)
print(img.mode)        # Color mode (e.g., RGB, L, RGBA)

Editing Images

# Resize:
resized = img.resize((200, 200))
# Crop:
cropped = img.crop((left, top, right, bottom))  # Coordinates tuple
# Rotate / Flip:
rotated = img.rotate(90)      # Degrees counter-clockwise
flipped = img.transpose(Image.FLIP_LEFT_RIGHT)

Changing Colour Modes

gray = img.convert('L')       # Convert to grayscale
rgba = img.convert('RGBA')    # Add alpha channel

Drawing on Images

You can draw lines, rectangles, ellipses, and more.

from PIL import ImageDraw

draw = ImageDraw.Draw(img)
draw.text((10, 10), "Hello!", fill=(255, 255, 255))  # Add text

Saving Images

img.save('new_image.jpg')                  # Saves in JPEG format
img.save('new_image.png', 'PNG')           # Specify format if needed

Working with Pixels

This only works on mutable modes like "RGB" or "RGBA".

# Access a pixel:
pixel = img.getpixel((50, 100))  # Get pixel at (x=50, y=100)
# Modify a pixel:
img.putpixel((50, 100), (255, 0, 0))  # Set pixel to red

Common Modes

Mode Description
1 Black and white
L Grayscale
RGB Red, Green, Blue
RGBA RGB with Alpha (transparency)
CMYK Cyan, Magenta, Yellow, Black

Example

# Open, Resize, Add Text, and Save
from PIL import Image, ImageDraw, ImageFont

# Open
img = Image.open('photo.jpg')

# Resize
img = img.resize((300, 300))

# Add Text
draw = ImageDraw.Draw(img)
draw.text((10, 10), "Sample", fill=(255, 255, 255))

# Save
img.save('photo_modified.jpg')