I’m thinking about whether to allow overwriting defaults for simplicity, and it seems like a good idea. It's crucial to convert to RGB when dealing with certain modes for JPEG images. We can choose to keep the original format for PNGs, but we should definitely catch exceptions and remind users to pip install Pillow. The user asked for a Python function, so I’ll focus on providing just that along with a minimal explanation, maybe mentioning os.walk as an optional detail. Here is a simple function using Pillow (PIL) to create thumbnails for all images in a folder:
python
from pathlib import Path
from PIL import Image
def create_thumbnails(input_folder, output_folder, size=(200, 200), overwrite=False):
"""
Create thumbnails for all images in input_folder and save them to output_folder.
:param input_folder: Path to the folder containing input images.
:param output_folder: Path to the folder where thumbnails will be saved.
:param size: Max (width, height) of the thumbnail.
:param overwrite: If True, overwrite existing files with the same name.
"""
input_folder = Path(input_folder)
output_folder = Path(output_folder)
output_folder.mkdir(parents=True, exist_ok=True)
valid_exts = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp"}
for img_path in input_folder.iterdir():
if not img_path.is_file():
continue
if img_path.suffix.lower() not in valid_exts:
continue
try:
with Image.open(img_path) as img:
# Create thumbnail in-place (preserves aspect ratio)
img.thumbnail(size)
# Compute output file path
out_path = output_folder / img_path.name
# Optionally avoid overwriting
if not overwrite and out_path.exists():
out_path = output_folder / f"{img_path.stem}_thumb{img_path.suffix}"
# Convert mode if needed for certain formats (e.g., JPEG)
if out_path.suffix.lower() in {".jpg", ".jpeg"} and img.mode in ("RGBA", "P"):
img = img.convert("RGB")
img.save(out_path)
print(f"Saved thumbnail: {out_path}")
except Exception as e:
print(f"Skipping {img_path.name}: {e}")
Usage example:
python
# Make sure Pillow is installed:
# pip install pillow
create_thumbnails(
input_folder="path/to/your/images",
output_folder="path/to/thumbnails",
size=(300, 300), # max width and height
overwrite=False
)
This will create thumbnails with the same filenames (or with _thumb appended if a file exists and overwrite=False), preserving aspect ratio, for all supported image files in the folder.