Build a Batch Grayscale Thumbnailer with Worker Pools
Data Structure DesignModel answerLast updated
Design and code a Pillow-based batch tool that grayscales and shrinks images, then scale it to many large files with multiprocessing, robust error handling, bounded memory and benchmarks.
You are asked to write a batch image tool in Python using the Pillow library.
Input: a list of image file paths and an output directory.
For every image:
- Convert it to grayscale.
- Resize it to a target size, keeping the result correct (think about what "correct" means for aspect ratio, orientation and transparency).
- Write the result into the output directory.
What to deliver:
- A first version that is simple and fine for a handful of small images.
- A second version that handles a large number of large images efficiently.
- A discussion, with code, of how you would use parallelism or concurrency (for example
ProcessPoolExecutor). Explain whether it helps for this workload and why, or when it would not. - Your approach to error handling, memory usage and file I/O.
- A plan for measuring performance and proving that the parallel version is actually faster.
State any assumptions you make, for example whether the target size is a bounding box or an exact output size.
Hints
Hint 1
Write a single worker function that takes a source path, a destination path and a size, never raises, and returns a small result object. The sequential and parallel versions then differ only in who calls it.
Hint 2
Think about what can make a grayscale and resize 'incorrect': EXIF rotation, images with transparency or palettes, upscaling small images, and aspect ratio distortion. Also consider how JPEG decoding can be made cheaper when you only need a small output.
Hint 3
Decide what crosses the process boundary (paths and small results, not pixels), what bounds memory (worker count, in-flight tasks, decoded image size), and what your benchmark compares (1 worker vs N workers, wall time and images per second, warm cache vs cold).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach in one paragraph
Build one pure worker function, process_one(src, dst, size) -> Result. It opens the image, normalizes it, makes it grayscale, shrinks it to fit the target, and publishes the output atomically. It never raises; failures come back as data. The simple version loops over this function. The scalable version hands the same function to a process pool. Parallelism becomes a scheduling choice rather than a rewrite.
Getting the transform right
- Orientation. Phone photos store rotation in EXIF. Apply
ImageOps.exif_transpose, or the output will be sideways. - Transparency and palettes.
convert("L")on an RGBA image silently drops alpha, so transparent pixels become arbitrary values. Composite onto a white background first. Palette (P) images should go through RGBA first. - Resize semantics. I treat the target as a bounding box:
thumbnailkeeps aspect ratio and never upscales. If the spec demands exact dimensions, useImageOps.fit(crop) orImageOps.pad(letterbox). Say which one you chose. - Resampling filter. Use LANCZOS for downscaling quality.
- Cheap JPEG decode.
im.draft("L", size)lets the JPEG decoder produce a grayscale image downscaled by 1/2, 1/4 or 1/8 during decoding. For big photos this is the largest single win in both time and memory. It is a no-op for other formats. - Atomic writes. Save to
dst + ".tmp"thenos.replace. A crash never leaves a truncated output.
Why processes help, and when they do not
Decoding and resampling a 24 MP photo costs tens to hundreds of milliseconds of CPU. Pillow releases the GIL in parts of decode and resize, but not everywhere, so threads scale unevenly. A ProcessPoolExecutor avoids the GIL and scales roughly linearly up to the physical core count.
It does not help when:
- There are few or tiny images. Startup and pickling overhead dominate. Run inline for small batches or
workers == 1. - Storage is the bottleneck (network drives, object storage, slow disks). More CPU just waits. Use threads or async fetching to feed a smaller process pool.
- You ship pixel data between processes. Pass paths and return small results. Each worker reads and writes its own files.
Memory
Peak memory is about workers × largest decoded image. A 100 MP RGB image is around 300 MB. Keep it bounded by:
- using
draftfor JPEGs, - capping
max_workers, - recycling workers with
max_tasks_per_child(Python 3.11+) if memory fragments, - limiting in-flight futures so millions of paths do not become millions of pending futures.
Error handling and edge cases
- Catch everything inside the worker (corrupt or truncated files, unsupported formats, permissions) and return
ok=Falseplus a message. One bad file must not abort the batch. - Keep Pillow's decompression-bomb guard on (it raises above roughly 179 MP), or set
Image.MAX_IMAGE_PIXELSdeliberately. - Different directories can contain the same basename. Deduplicate output names in the parent before dispatching.
- Animated GIFs and multi-page TIFFs: process only the first frame, and state that as a scope decision.
- Images smaller than the target stay at their size.
- An empty input returns an empty list.
- A killed worker (for example OOM) raises
BrokenProcessPool. Surface it clearly instead of hanging.
Code
from __future__ import annotations
import os
import time
from collections import Counter
from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
from dataclasses import dataclass
from pathlib import Path
from PIL import Image, ImageOps
@dataclass(frozen=True)
class Result:
src: str
dst: str | None
ok: bool
error: str | None = None
seconds: float = 0.0
def _to_gray(im: Image.Image) -> Image.Image:
if im.mode == "P":
im = im.convert("RGBA")
if im.mode in ("RGBA", "LA"):
bg = Image.new("RGB", im.size, (255, 255, 255))
rgba = im.convert("RGBA")
bg.paste(rgba, mask=rgba.getchannel("A"))
im = bg
return im.convert("L")
def process_one(src: str, dst: str, size: tuple[int, int]) -> Result:
t0 = time.perf_counter()
tmp = dst + ".tmp"
try:
with Image.open(src) as im:
im.draft("L", size)
im = ImageOps.exif_transpose(im)
im = _to_gray(im)
im.thumbnail(size, Image.Resampling.LANCZOS)
im.save(tmp, format="PNG")
os.replace(tmp, dst)
return Result(src, dst, True, seconds=time.perf_counter() - t0)
except Exception as exc:
if os.path.exists(tmp):
os.remove(tmp)
return Result(src, None, False, f"{type(exc).__name__}: {exc}",
time.perf_counter() - t0)
def plan_outputs(paths: list[str], out_dir: Path) -> list[str]:
totals = Counter(Path(p).stem for p in paths)
seen: Counter[str] = Counter()
outs = []
for p in paths:
stem = Path(p).stem
if totals[stem] > 1:
seen[stem] += 1
stem = f"{stem}_{seen[stem]}"
outs.append(str(out_dir / f"{stem}.png"))
return outs
def process_images(paths, out_dir, size=(512, 512),
max_workers=None, max_in_flight=None):
out = Path(out_dir)
out.mkdir(parents=True, exist_ok=True)
jobs = list(zip(paths, plan_outputs(paths, out)))
if not jobs:
return []
workers = max_workers or os.cpu_count() or 1
# Small batch or single worker: run inline, no process overhead.
if workers == 1 or len(jobs) < 4:
return [process_one(s, d, size) for s, d in jobs]
limit = max_in_flight or workers * 4
results = [None] * len(jobs)
it = iter(enumerate(jobs))
pending = {}
with ProcessPoolExecutor(max_workers=workers) as pool:
def submit_next() -> bool:
try:
i, (s, d) = next(it)
except StopIteration:
return False
pending[pool.submit(process_one, s, d, size)] = i
return True
for _ in range(limit):
if not submit_next():
break
while pending:
done, _ = wait(pending, return_when=FIRST_COMPLETED)
for fut in done:
i = pending.pop(fut)
try:
results[i] = fut.result()
except Exception as exc: # e.g. BrokenProcessPool
s, d = jobs[i]
results[i] = Result(s, None, False, f"{type(exc).__name__}: {exc}")
submit_next()
return results
Measuring performance
- Use a fixed, realistic dataset (mixed sizes and formats) and compare 1 worker vs 2, 4, 8, ... N.
- Report wall time, images per second and speedup. Compare against ideal linear speedup and find where it flattens.
- Separate cold-cache and warm-cache runs, since disk caching can hide I/O costs.
- Compare with and without
draft, and processes versus threads. - Record peak resident memory per worker, and the per-image
secondsdistribution (p50 and p99) to spot outliers. - Run several repetitions and report the median.
Complexity
- Time: proportional to total pixels decoded plus resized. Wall time is about that divided by
min(workers, cores)until I/O saturates.draftcan cut decoded pixels up to 64x for JPEGs. - Space: O(workers × peak decoded image) across workers, plus O(max_in_flight) futures in the parent.
Common mistakes
- Ignoring EXIF orientation or alpha.
- Using
resizewith a fixed size and distorting aspect ratio. - Sending image bytes through the pool instead of paths.
- Submitting every task at once for a huge input.
- Letting an exception in one image kill the whole run.
- Claiming a speedup without a benchmark, or using processes for a tiny batch.