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.
pip install Pillow
Python code
18 linesfrom 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
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
- Use `src_path.rglob('*.jpg')` to include files in subdirectories recursively
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.