Prerequisites
Ensure you have Python 3 installed alongside the Pillow library. Install it via pip:
pip install Pillow
The Python Implementation
This implementation slugifies your source filename (removing spaces and special characters), enforces a maximum bounding box size, drops metadata overhead, and converts files into the highly optimized .webp format.
import os
import re
from PIL import Image
def generate_web_thumbnail(source_path, output_dir, max_size=(300, 300)):
"""
Resizes an image to web-safe dimensions, optimizes it,
and saves it to an output directory using a clean filename.
"""
# Ensure the output directory exists
os.makedirs(output_dir, exist_ok=True)
# 1. Generate a web-safe, slugified filename
base_name = os.path.splitext(os.path.basename(source_path))[0]
# Convert to lowercase and replace non-alphanumeric characters with hyphens
clean_name = re.sub(r'[^a-z0-9]+', '-', base_name.lower()).strip('-')
output_filename = f"{clean_name}-thumb.webp"
output_path = os.path.join(output_dir, output_filename)
try:
# 2. Open and process the image
with Image.open(source_path) as img:
# Convert RGBA/Palette images to RGB for proper WebP/JPEG compression
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")
# Use thumbnail method to maintain the aspect ratio precisely
img.thumbnail(max_size, Image.Resampling.LANCZOS)
# 3. Save with web optimization flags
img.save(output_path, "WEBP", quality=80, optimize=True)
print(f"Success: Generated thumbnail at {output_path}")
return output_path
except Exception as e:
print(f"Error processing {source_path}: {e}")
return None
# Example Usage
if __name__ == "__main__":
generate_web_thumbnail(
source_path="Raw Image File 2026! @Copy.jpg",
output_dir="./dist/thumbnails"
)
# Resulting output file: ./dist/thumbnails/raw-image-file-2026-copy-thumb.webp
How It Works
- Aspect Ratio Preservation: The
.thumbnail()method natively prevents stretching by fitting the image entirely within your specified bounds. - Slugification: The regex block drops raw spaces and dangerous characters, preventing broken web paths or encoding issues.
- WebP Encoding: Converts the payload to
.webpwith an 80% optimization pass to keep file payloads tiny without sacrificing visual clarity.