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


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:
        if img.mode == "RGBA":
            img = img.convert("RGB")
        img.save(output_path, "WEBP", quality=quality, optimize=True)


# Batch process images
for p in Path("images").glob("*.jpg"):
    compress_image(p, p.with_suffix(".webp"))

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 *.jpg

Watch this video on modern image formats and optimization (15 min):

Modern Image Optimization (15 min)

Tools for image optimization: