How to Batch Resize Images in Python with pathlib and Pillow

Batch resize all JPG images from a source folder and save to a destination folder using pathlib and Pillow.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 12 views 0 copies

Requires third-party packages — install first
pip install Pillow

Python code

18 lines
Python 3.9+
from pathlib import Path
from PIL import Image

def batch_resize_images(src_dir: str, dest_dir: str, size: tuple[int, int] = (800, 600)) -> None:
    src_path = Path(src_dir)
    dest_path = Path(dest_dir)
    dest_path.mkdir(parents=True, exist_ok=True)
    
    for img_path in src_path.glob("*.jpg"):
        if not img_path.is_file():
            continue
        with Image.open(img_path) as img:
            resized = img.resize(size)
            output_path = dest_path / f"resized_{img_path.name}"
            resized.save(output_path)

if __name__ == "__main__":
    batch_resize_images("photos", "photos_resized")

Output

stdout
No stdout output, but after running the script, the destination folder 'photos_resized' will contain resized versions of every .jpg from 'photos', named like 'resized_photo1.jpg'.

How it works

The function uses Path.glob to find all .jpg files in the source directory, filtering out any non-file entries with is_file(). For each image, it opens the file in a context manager, resizes it to 800x600, and saves with a 'resized_' prefix. The mkdir(parents=True, exist_ok=True) ensures the destination folder exists before writing, making the script idempotent. This pattern is ideal for automation because it handles file paths cross-platform and cleans up resources safely.

Common mistakes

  • Forgetting to import PIL/Pillow, causing ModuleNotFoundError
  • Using `glob('*.jpeg')` when files are .jpg, missing matches
  • Not using `is_file()` and trying to process directories that match the pattern
  • Overwriting original images by saving to the same directory without a prefix

Variations

  1. Use `src_path.rglob('*.jpg')` to include files in subdirectories recursively
  2. Add error handling with try/except to skip corrupt images

Real-world use cases

  • Preprocessing product photos to a uniform size before uploading to an e-commerce platform.
  • Creating thumbnail sets for a photo gallery or content management system.
  • Reducing image file sizes for email attachments or web asset uploads.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Automation & scripting

Related tutorials and quizzes for this topic.