Select images
Compress Image
For mobile users and regions with limited connectivity, compression can be the difference between a usable site and an unusable one.
Lossless vs Lossy Compression
Lossless
Lossless compression algorithms (PNG, GIF, lossless WebP, FLIF in the past) reduce file size without altering the visual information. They’re ideal for images where fidelity and exact reproduction matter — icons, logos, screenshots, and images containing text or sharp edges.
Lossy
Lossy compression (JPEG, lossy WebP, AVIF) discards some information, relying on human perception to hide differences. For photographs, lossy compression is highly effective — large file size reductions with minimal perceived quality loss when tuned correctly.
How Compression Works (High Level)
At a high level, compression exploits redundancy and perceptual irrelevance. Redundancy means repeated patterns can be encoded more compactly. Perceptual irrelevance means certain image details are less important to the human eye — color detail in smooth areas, or frequencies beyond human perception — and can be removed or approximated. Formats use transforms (like discrete cosine transform or variants), quantization, and entropy coding to achieve compression.
Common Image Formats and Their Compression Characteristics
- JPEG: Lossy, excellent for photographs, adjustable quality factor, widely supported.
- PNG: Lossless, supports transparency, great for graphics, icons, and screenshots.
- GIF: Lossless-ish for limited palettes, supports simple animation, limited to 256 colors.
- WebP: Supports both lossy and lossless, transparency, and animation. Often smaller than JPEG/PNG at similar quality.
- AVIF: Modern, high-efficiency format with strong compression; growing support across browsers and tools.
- SVG: Vector format (not raster compression) — infinitely scalable and typically tiny for icons/illustrations.
Practical Compression Techniques
1. Choose the Right Format
Pick a format that fits the image content. Photographs: JPEG or WebP/AVIF. Graphics with transparency: PNG or lossless WebP. Animated content: animated WebP or GIF (or APNG).
2. Resize Before Compressing
Serve images at the resolution they will be displayed. There’s no benefit to sending a 4000px-wide image to a mobile user who sees it at 400px. Resize to target dimensions before compression to avoid unnecessary bytes.
3. Use Quality Settings Wisely
For JPEG, quality values between 70 and 85 often balance size and quality. For WebP/AVIF, equivalent quality can achieve smaller sizes; test visually. Use perceptual quality metrics (SSIM, VMAF) for automated tuning if necessary.
4. Strip Metadata
EXIF data (camera info, GPS coordinates) increases file size. Remove it when not needed for display or for privacy. Tools like ExifTool, ImageMagick, and many online optimizers handle metadata stripping.
5. Optimize Color Depth and Palettes
Reduce color depth for images that don't need full 24-bit color. GIFs and indexed PNGs reduce palette size. For screenshots, PNG with palette optimization (pngquant) can drastically reduce size without visible change.
6. Use Better Encoders
Modern encoders (MozJPEG, libwebp, AVIF encoders like libavif) produce smaller files than older encoders. They include advanced optimizations such as progressive scans, trellis quantization, and better Huffman coding.
7. Progressive/Interlaced Files
Progressive JPEG and interlaced PNG show a low-quality preview quickly and refine it as more data arrives. This improves perceived performance for users on slow networks.
8. Use a CDN with Format Negotiation
Image CDNs detect browser capabilities and serve WebP/AVIF automatically when supported, falling back to JPEG/PNG otherwise. This reduces the need to manually maintain many file variants.
Tools and Workflows
Desktop Tools
Photoshop, Affinity Photo, and GIMP provide export options with quality sliders and previews. Use them for manual tuning when visual fidelity is critical.
Command-line Tools
Command-line tooling is essential for automation and reproducibility:
jpegoptim --max=85 image.jpg
Libraries
Sharp (Node.js), Pillow (Python), and libvips are excellent for server-side image processing and batch jobs. They’re fast and integrate into build pipelines.
Automated Pipelines
Integrate compression into your CI/CD or build process (Webpack, Gulp, Hugo pipelines). For dynamic sites, use serverless functions or image CDNs that compress and cache on demand.
Examples: Command-line Recipes
JPEG Optimization with MozJPEG
cjpeg -quality 80 -optimize -progressive -outfile out.jpg in.ppm
PNG Optimization with pngquant
pngquant --quality=60-80 --speed=1 --strip --output out.png in.png
WebP Conversion
cwebp -q 80 in.jpg -o out.webp
Tip: Always compare original vs compressed images at 1:1 zoom before deploying large batches. Use visual diff tools or automated metrics when available.
Advanced Techniques: Perceptual and Content-aware Compression
Perceptual compression uses human-vision models to determine which parts of an image can be compressed more aggressively. Content-aware techniques can preserve faces and text while compressing background areas more. These require specialized tools and sometimes machine learning inferencing but can provide superior results for important imagery like product photos or portraits.
Measuring Quality: Visual and Automated Metrics
Quality measurement can be subjective. For automated systems, use metrics like:
- PSNR (Peak Signal-to-Noise Ratio) — basic but not perceptually aligned.
- SSIM — Structural similarity index, better for perceived changes.
- VMAF — More advanced video/image perception metric developed by Netflix.
Combine automated metrics with spot visual checks for a robust strategy.
Common Pitfalls and How to Avoid Them
- Over-compressing: Produces visible artifacts — blockiness, ringing, and color banding. Always test different quality levels.
- Ignoring device pixel ratio: Provide 2×/3× assets for retina displays to avoid blurry images.
- Converting formats blindly: Don't convert PNG with transparency to JPEG; you'll lose the alpha channel.
- Losing color fidelity: Watch out for color profile mismatches; convert to sRGB for the web when necessary.