python
39 lines · 8 steps
Batch image resizing with Pillow
Walk a folder, shrink every supported image to fit a bounding box, and write clean copies to a destination.
Explained by
highlit
1from pathlib import Path
2
3from PIL import Image, ImageOps
4
5SUPPORTED = {".jpg", ".jpeg", ".png", ".webp"}
6
7
8def resize_folder(
9 source: Path,
10 dest: Path,
11 max_size: tuple[int, int] = (1280, 1280),
12 quality: int = 85,
13) -> list[Path]:
14 dest.mkdir(parents=True, exist_ok=True)
15 written: list[Path] = []
16
17 for path in sorted(source.iterdir()):
18 if path.suffix.lower() not in SUPPORTED:
19 continue
20
21 try:
22 with Image.open(path) as img:
23 img = ImageOps.exif_transpose(img)
24 img.thumbnail(max_size, Image.Resampling.LANCZOS)
25
26 out_path = dest / path.name
27 save_kwargs = {"optimize": True}
28
29 if img.mode in ("RGBA", "P") and path.suffix.lower() in {".jpg", ".jpeg"}:
30 img = img.convert("RGB")
31 if path.suffix.lower() in {".jpg", ".jpeg", ".webp"}:
32 save_kwargs["quality"] = quality
33
34 img.save(out_path, **save_kwargs)
35 written.append(out_path)
36 except (OSError, Image.DecompressionBombError) as exc:
37 print(f"skipping {path.name}: {exc}")
38
39 return written
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A whitelist set plus suffix checks keeps a batch job from choking on unrelated files.
- 2thumbnail resizes in place while preserving aspect ratio, so a bounding box never distorts an image.
- 3Wrapping each file in its own try/except lets one corrupt image fail without aborting the whole run.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
python
from flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/batch-image-resizing-with-pillow-explained-python-1196/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.