import os
from PIL import Image
import glob
def create_thumbnails(input_folder, thumbnail_size=(128, 128), output_folder=None, quality=85):
"""
Create thumbnails for all images in the specified input folder.
Args:
input_folder (str): Path to the folder containing images.
thumbnail_size (tuple): Tuple of (width, height) for the thumbnail size.
The image will be resized to fit within this size while preserving aspect ratio.
output_folder (str, optional): Path to save thumbnails. If None, creates a 'thumbnails' subfolder
in the input_folder.
quality (int): JPEG quality for thumbnails (1-95). Only applies if saving as JPEG.
Returns:
list: List of paths to created thumbnail files.
Supported formats: JPEG, PNG, BMP, GIF, TIFF, WebP.
"""
if not os.path.exists(input_folder):
raise ValueError(f"Input folder '{input_folder}' does not exist.")
if output_folder is None:
output_folder = os.path.join(input_folder, 'thumbnails')
os.makedirs(output_folder, exist_ok=True)
# Common image extensions (case-insensitive)
extensions = ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.gif', '*.tiff', '*.webp']
image_files = []
for ext in extensions:
image_files.extend(glob.glob(os.path.join(input_folder, ext.lower())))
image_files.extend(glob.glob(os.path.join(input_folder, ext.upper())))
thumbnails_created = []
for img_path in image_files:
try:
with Image.open(img_path) as img:
# Create a thumbnail copy (preserves aspect ratio, fits within size)
thumb = img.copy()
thumb.thumbnail(thumbnail_size)
# Determine output filename
base_name, ext = os.path.splitext(os.path.basename(img_path))
thumb_name = f"{base_name}_thumb.jpg" # Save as JPEG for consistency and smaller size
thumb_path = os.path.join(output_folder, thumb_name)
# Save thumbnail
thumb.save(thumb_path, 'JPEG', quality=quality)
thumbnails_created.append(thumb_path)
print(f"Created thumbnail: {thumb_path}")
except Exception as e:
print(f"Error processing {img_path}: {str(e)}")
print(f"Created {len(thumbnails_created)} thumbnails in '{output_folder}'.")
return thumbnails_created
Usage Example:
# Create thumbnails for images in '/path/to/images' folder
thumbnails = create_thumbnails('/path/to/images', thumbnail_size=(256, 256))
This function:
- Automatically detects common image formats.
- Preserves aspect ratio when resizing.
- Saves thumbnails as JPEG for smaller file sizes.
- Handles errors gracefully (skips invalid files).
- Creates the output folder if it doesn't exist.
- Returns a list of thumbnail paths for further use.