I'm starting to build a Python function, as requested. The core focus is making a function to accept a folder of images and produce corresponding thumbnails. The first step involves clearly defining the function's inputs and outputs to ensure it's easy to use and provides the expected results.
Mapping Out the Process
I've identified the key tools for this task: Pillow for image processing and pathlib for file management, which I find cleaner. Next, I'm setting functional requirements like folder paths, thumbnail dimensions, and error handling for non-image files and missing destination folders. I'm ready to begin drafting the Python code, starting with imports.
Developing the Iteration
I'm now iterating through the input directory. I've set up an image extension filter to ensure only image files are processed. I'm using pathlib to handle path operations for readability and easy creation of the output directory if it doesn't exist. Now, I'll integrate the image processing logic for the core functionality.
Integrating Image Handling
I've finalized the image processing loop within the function. I'm handling the thumbnail generation with Image.thumbnail() to maintain aspect ratio, which I think is best practice for thumbnail creation. I am going to preserve the original image format, to avoid unnecessary format conversions. I'm also including try-except blocks for robust error handling. Docstrings and type hints will be included for clarity.
Expanding Documentation & Examples
I'm now focusing on comprehensive documentation. I'll include the necessary pip install Pillow command for users, ensuring they can easily get the required library. I'll thoroughly explain the code's functionality, breaking it down line-by-line and block-by-block for clarity. Finally, a clear usage example will be provided, illustrating how to call and utilize the function effectively. I'm aiming for complete user understanding.
Refining Documentation Details
I'm wrapping up the documentation phase by adding a "Bonus/Advanced" section. I'll briefly touch on parallel processing using concurrent.futures, although I'm keeping the core function straightforward per the original request. The formatting is also being carefully checked for clarity with code blocks. Now, I'm ready to generate the final output.
To do this, you will need the Pillow library (the modern version of PIL), which is the standard Python library for image manipulation.
Prerequisites
First, install the library via your terminal/command prompt:
bash
pip install Pillow
The Python Solution
Here is a robust script using the modern pathlib module. It handles creating the output directory, preserves aspect ratios, and includes error handling.
python
import os
from pathlib import Path
from PIL import Image
def create_thumbnails(source_folder, output_folder, size=(128, 128)):
"""
Generates thumbnails for all images in a specific folder.
Args:
source_folder (str): Path to the folder containing original images.
output_folder (str): Path where thumbnails will be saved.
size (tuple): Max (width, height) for the thumbnail.
Aspect ratio is preserved.
"""
# Convert strings to Path objects
source_path = Path(source_folder)
output_path = Path(output_folder)
# Create output directory if it doesn't exist
output_path.mkdir(parents=True, exist_ok=True)
# supported extensions
extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp'}
print(f"Processing images from: {source_path}")
count = 0
# Iterate through files in the source folder
for file_path in source_path.iterdir():
# Check if file is an image based on extension
if file_path.suffix.lower() in extensions:
try:
with Image.open(file_path) as img:
# Create copies to avoid locking the file
img_copy = img.copy()
# .thumbnail() modifies the image in-place and preserves aspect ratio
img_copy.thumbnail(size)
# Create new filename (e.g., "photo.jpg" -> "thumb_photo.jpg")
thumb_filename = f"thumb_{file_path.name}"
destination = output_path / thumb_filename
# Save the file
img_copy.save(destination)
print(f"Generated: {thumb_filename}")
count += 1
except Exception as e:
print(f"Error processing {file_path.name}: {e}")
print(f"\nSuccess! {count} thumbnails created in '{output_folder}'.")
# --- Usage Example ---
if __name__ == "__main__":
# Change these paths to your actual folders
input_dir = "my_photos"
output_dir = "my_photos/thumbnails"
# Check if input dir exists to avoid error in the example
if not os.path.exists(input_dir):
os.makedirs(input_dir)
print(f"Created dummy folder '{input_dir}'. Please put images in it and run again.")
else:
create_thumbnails(input_dir, output_dir, size=(300, 300))
Key Features of this code:
Preserves Aspect Ratio: The img.thumbnail() method is smart. If you ask for (300, 300) and give it a landscape photo that is 1920x1080, it will resize it to 300x168, fitting it inside the box without distorting or stretching the image.
Non-destructive: It saves the files with a prefix (e.g., thumb_image.jpg) into a separate folder, ensuring your original high-res images are never overwritten.
Format support: It converts formats like BMP, PNG, WEBP, and JPG.
pathlib: Uses modern Python path handling, which works seamlessly across Windows, macOS, and Linux.
FAQ
Q: How do I make the file size smaller (compression)?
You can modify the img_copy.save() line to include a quality parameter:
python
# Quality ranges from 1 (worst) to 95 (best). Default is usually 75.
img_copy.save(destination, quality=85, optimize=True)
Q: How do I force a square thumbnail (crop)?
The script above fits the image within the size. If you want exact squares (e.g., for a grid layout), you need to use ImageOps.fit: