How to Resize Hundreds of Images in Batch with Python
Resize every image in a folder to a target size using Pillow, creating a new subfolder for processed files.
pip install Pillow
Python code
21 linesimport os
from PIL import Image
def resize_images_in_batch(directory, output_size=(800, 600)):
if not os.path.exists(directory):
print(f"Directory {directory} does not exist.")
return
output_dir = os.path.join(directory, "resized")
os.makedirs(output_dir, exist_ok=True)
for filename in os.listdir(directory):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
filepath = os.path.join(directory, filename)
with Image.open(filepath) as img:
img_resized = img.resize(output_size, Image.Resampling.LANCZOS)
output_path = os.path.join(output_dir, filename)
img_resized.save(output_path)
print(f"Resized and saved: {output_path}")
if __name__ == "__main__":
target_dir = "images"
resize_images_in_batch(target_dir, (800, 600))
Output
Resized and saved: images/resized/photo1.jpg
Resized and saved: images/resized/photo2.png
Resized and saved: images/resized/screenshot.bmp
How it works
This script loops through all files in a given directory, filtering by common image extensions. For each image it opens the file with Pillow's Image.open, resizes it using the high-quality LANCZOS resampling filter, and saves the result into a resized subfolder. Using os.makedirs(..., exist_ok=True) avoids errors if the subfolder already exists. The script is designed as a reusable function that takes a directory path and target output size as parameters.
Common mistakes
- Forgetting to install Pillow (`pip install Pillow`) before running the script.
- Using `os.listdir()` without filtering for image file extensions, which may try to resize directories or non-image files.
- Overwriting original images instead of saving resized copies to a separate folder.
Variations
- Use `pathlib.Path.rglob('*')` to recursively process images in subdirectories.
- Resize proportionally based on max width or height instead of forcing exact dimensions.
Real-world use cases
- Preprocessing product photos for an e-commerce site to ensure uniform thumbnail sizes.
- Downscaling high-resolution camera images before uploading them to a cloud storage bucket.
- Generating compressed image assets for a mobile app to reduce bundle size.
Sponsored
More from Automation & scripting
- Batch Rename Hundreds of Files in Python easy
- Build a Command-Line Password Generator in Python easy
- Build a Complete Web Scraper with Requests and BeautifulSoup in Python medium
- Build a Network Ping Monitor in Python medium
- Create a Local Search Engine to Instantly Find Files on Your Computer in Python medium
- Create a Simple HTTP File Server in Python easy
Keep learning
Related tutorials and quizzes for this topic.