Optimizing images for web
Published April 30, 2025 · 10 min read
Image generated with ChatGPT
Published April 30, 2025 · 10 min read
This is a simple script to optimize images for web.
from PIL import Image
import os
def optimize_image(input_path, output_path=None, quality=85, max_width=None, max_height=None):
"""
Compress and optionally resize an image without visible quality loss.
- JPEG: uses quality and optimization.
- PNG: uses optimization and no quality parameter.
"""
if output_path is None:
output_path = input_path # overwrite by default
with Image.open(input_path) as img:
# Resize if max dimensions are set
if max_width or max_height:
img.thumbnail((max_width or img.width, max_height or img.height))
# Get format (JPEG, PNG, etc.)
img_format = img.format
# Convert PNGs with transparency to RGB to avoid issues
if img_format == "PNG" and img.mode in ("RGBA", "LA"):
img = img.convert("RGBA")
save_params = {
"optimize": True
}
if img_format == "JPEG":
save_params["quality"] = quality
save_params["progressive"] = True
img.save(output_path, format=img_format, **save_params)
optimize_image("input.png", "output-optimized.png", quality=50, max_width=480)