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

Walkthrough

Space play step click any line
Three takeaways
  1. 1A whitelist set plus suffix checks keeps a batch job from choking on unrelated files.
  2. 2thumbnail resizes in place while preserving aspect ratio, so a bounding box never distorts an image.
  3. 3Wrapping each file in its own try/except lets one corrupt image fail without aborting the whole run.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Batch image resizing with Pillow — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code