Spaces:
Sleeping
Sleeping
metadata
title: 'Images: Compression'
original_url: https://tds.s-anand.net/#/image-compression?id=images-compression
downloaded_at: '2025-06-08T23:26:15.003538'
Images: Compression
Image compression is essential when deploying apps. Often, pages have dozens of images. Image analysis runs over thousands of images. The cost of storage and bandwidth can grow over time.
Here are things you should know when you’re compressing images:
- Image dimensions are the width and height of the image in pixels. This impacts image size a lot
- Lossless compression (PNG, WebP) preserves exact data
- Lossy compression (JPEG, WebP) removes some data for smaller files
- Vector formats (SVG) scale without quality loss
- WebP is the modern standard, supporting both lossy and lossless
Here’s a rule of thumb you can use as of 2025.
- Use SVG if you can (i.e. if it’s vector graphics or you can convert it to one)
- Else, reduce the image to as small as you can, and save as (lossy or lossless) WebP
Common operations with Python:
from pathlib import Path
from PIL import Image
import io
async def compress_image(input_path: Path, output_path: Path, quality: int = 85) -> None:
"""Compress an image while maintaining reasonable quality."""
with Image.open(input_path) as img:
# Convert RGBA to RGB if needed
if img.mode == 'RGBA':
img = img.convert('RGB')
# Optimize for web
img.save(output_path, 'WEBP', quality=quality, optimize=True)
# Batch process images
paths = Path('images').glob('*.jpg')
for p in paths:
await compress_image(p, p.with_suffix('.webp'))Copy to clipboardErrorCopied
Command line tools include cwebp, pngquant, jpegoptim, and ImageMagick.
# Convert to WebP
cwebp -q 85 input.png -o output.webp
# Optimize PNG
pngquant --quality=65-80 image.png
# Optimize JPEG
jpegoptim --strip-all --all-progressive --max=85 image.jpg
# Convert and resize
convert input.jpg -resize 800x600 output.jpg
# Batch convert
mogrify -format webp -quality 85 *.jpgCopy to clipboardErrorCopied
Watch this video on modern image formats and optimization (15 min):
Tools for image optimization:
- squoosh.app: Browser-based compression
- ImageOptim: GUI tool for Mac
- sharp: Node.js image processing
- Pillow: Python imaging library
[Previous
Markdown](#/markdown)
[Next
Static hosting: GitHub Pages](#/github-pages)
