Lesson 32 of 34

Pillow: Image Automation

Pillow is the practical toolkit for resizing, cropping, converting, compositing, and inspecting images. A short script can replace a lot of repetitive manual editing.

Bash
python -m pip install pillow
Python
from pathlib import Path
from PIL import Image, ImageOps

source_dir = Path("originals")
output_dir = Path("thumbnails")
output_dir.mkdir(exist_ok=True)

for path in source_dir.glob("*.*"):
    try:
        with Image.open(path) as image:
            # Correct phone-camera orientation using EXIF metadata.
            image = ImageOps.exif_transpose(image)
            image.thumbnail((800, 800), Image.Resampling.LANCZOS)
            if image.mode not in ("RGB", "L"):
                image = image.convert("RGB")
            destination = output_dir / f"{path.stem}.jpg"
            image.save(destination, quality=85, optimize=True)
            print(f"Wrote {destination}")
    except (OSError, ValueError) as error:
        print(f"Skipped {path}: {error}")
Python
from PIL import Image, ImageDraw, ImageFont

with Image.open("photo.jpg").convert("RGBA") as photo:
    overlay = Image.new("RGBA", photo.size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(overlay)
    font = ImageFont.truetype("DejaVuSans.ttf", 36)
    text = "© Example Studio"
    box = draw.textbbox((0, 0), text, font=font)
    width = box[2] - box[0]
    x, y = photo.width - width - 24, photo.height - 60
    draw.rounded_rectangle((x - 12, y - 8, photo.width - 12, photo.height - 10), fill=(0, 0, 0, 130), radius=8)
    draw.text((x, y), text, font=font, fill="white")
    Image.alpha_composite(photo, overlay).convert("RGB").save("watermarked.jpg", quality=90)
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.