Image Optimization Guide — Improve Page Speed with WebP Conversion
Why Image Optimization Matters
Images account for an average of 40–60% of a web page's total transfer size. Optimizing images is one of the most effective ways to improve page load speed.
Google's PageSpeed Insights (PSI) frequently flags unoptimized images as "opportunities for improvement." Among the Core Web Vitals, LCP (Largest Contentful Paint) measures how quickly the largest content element appears, and hero image optimization directly impacts this score.
Improving load speed not only enhances user experience but also positively affects SEO rankings.
Comparing Image Formats
Here's a comparison of the major image formats used on the web:
| Format | Compression | Transparency | Animation | Browser Support | Primary Use |
|---|---|---|---|---|---|
| JPEG | Lossy | No | No | All | Photos |
| PNG | Lossless | Yes | No | All | Logos, screenshots |
| GIF | Lossless | Yes | Yes | All | Simple animations |
| WebP | Both | Yes | Yes | 97%+ | General (recommended) |
| AVIF | Lossy | Yes | Yes | 93%+ | High compression needs |
| SVG | Vector | Yes | Yes | All | Icons, shapes |
JPEG
The most widely used format for photographs. Lossy compression achieves high compression ratios, but repeated compression and saving degrades quality. It does not support transparency.
PNG
Lossless compression ensures no quality loss, and it supports transparency. Ideal for logos, screenshots, and text-heavy images, but file sizes tend to be large for photographs.
WebP
Developed by Google, WebP combines the strengths of both JPEG and PNG. It supports both lossy and lossless compression, as well as transparency and animation.
Benefits of Converting to WebP
WebP can reduce file sizes by 25–35% compared to JPEG and up to 80% compared to PNG.
Real-World Compression Examples
| Original Image | JPEG (Quality 85) | WebP (Quality 80) | Reduction |
|---|---|---|---|
| Landscape photo (4000×3000) | 2.1 MB | 1.4 MB | 33% |
| Product photo (1200×800) | 450 KB | 290 KB | 36% |
| Screenshot (1920×1080) | 680 KB | 180 KB | 74% |
WebP's compression efficiency is particularly impressive for screenshots and images with large areas of uniform color.
WebP Quality Settings
The WebP quality parameter ranges from 0 to 100. Recommended values by use case:
| Use Case | Recommended Quality | Reason |
|---|---|---|
| Thumbnails | 60–70 | Degradation is not noticeable at small display sizes |
| General images | 75–85 | Good balance between quality and file size |
| High-quality photos | 85–95 | Minimizes visual degradation |
| Lossless | 100 | Larger file size but no quality loss |
Compression Techniques
Lossy Compression Tips
Lossy compression reduces file size by removing information that is imperceptible to the human eye.
- Appropriate quality level: Saving at around quality 80 produces no noticeable visual degradation for most use cases
- Chroma subsampling: A technique that reduces color information. 4:2:0 is common and significantly reduces file size
- Progressive rendering: Displays a rough overview first, then gradually sharpens. Improves perceived speed
Lossless Compression Tips
Methods that reduce file size without any quality degradation:
- Remove metadata: Delete EXIF data (date, GPS coordinates, camera info). Also recommended for privacy protection
- Optimize color palette: For images with few colors, optimize the palette size
- PNG optimization tools: Use dedicated tools like pngquant and optipng
Implementing Responsive Images
Serving appropriately sized images based on device screen size prevents unnecessary data transfer on mobile devices.
Using srcset and sizes
<img
src="image-800.webp"
srcset="
image-400.webp 400w,
image-800.webp 800w,
image-1200.webp 1200w,
image-1600.webp 1600w
"
sizes="
(max-width: 640px) 100vw,
(max-width: 1024px) 50vw,
33vw
"
alt="Product photo"
width="800"
height="600"
>
This specification allows the browser to automatically select the optimal image based on screen size and device pixel ratio.
Using the picture Element for Format Negotiation
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Landscape photo" width="800" height="600">
</picture>
This serves AVIF to supported browsers, WebP to WebP-capable browsers, and falls back to JPEG for others.
Lazy Loading
Loading images outside the viewport later can dramatically improve initial page load speed.
Native Lazy Loading
<!-- Add loading="lazy" to below-the-fold images -->
<img src="below-fold.webp" loading="lazy" alt="Description" width="800" height="600">
<!-- Do NOT add it to above-the-fold images (impacts LCP) -->
<img src="hero.webp" alt="Main image" width="1200" height="600">
Important: Never set loading="lazy" on LCP elements (main images at the top of the page). Lazy loading will worsen your LCP score.
Priority Control with fetchpriority
<!-- Load hero image with high priority -->
<img src="hero.webp" fetchpriority="high" alt="Main image" width="1200" height="600">
<!-- Load decorative images with low priority -->
<img src="decoration.webp" fetchpriority="low" loading="lazy" alt="" width="200" height="200">
Preventing CLS (Layout Shift)
Layout shifts caused by image loading negatively impact the Core Web Vitals CLS score.
Always Specify width and height
<!-- Specifying width and height lets the browser reserve space in advance -->
<img src="photo.webp" width="800" height="600" alt="Photo">
Use aspect-ratio
.responsive-image {
width: 100%;
height: auto;
aspect-ratio: 4 / 3;
}
Optimization Checklist
A summary of items to verify when optimizing images for your website:
Format Selection
- Are photos converted to WebP (or AVIF)?
- Are logos and icons using SVG?
- Is a fallback provided for unsupported browsers?
Size Optimization
- Are images not excessively larger than their display size?
- Are 2x images prepared for Retina displays?
- Are multiple sizes provided via srcset?
Delivery Optimization
- Is
loading="lazy"set on below-the-fold images? - Is
fetchpriority="high"set on the hero image? - Are images served through a CDN (Content Delivery Network)?
Quality and CLS
- Is an appropriate compression quality set (75–85 as a guideline)?
- Do all images have
widthandheightspecified? - Has unnecessary metadata (EXIF, etc.) been removed?
Image Compression Algorithms Explained
How Lossless Compression Works
Lossless compression reduces file size while preserving every bit of the original image data. It works by eliminating redundant patterns in the data.
LZW (Lempel-Ziv-Welch)
Used by GIF. The algorithm builds a dictionary of repeating patterns found in the image data and replaces recurring sequences with shorter reference codes. This works well for images with large areas of uniform color but provides minimal compression for complex photographs.
DEFLATE
Used by PNG. It combines two algorithms:
- LZ77: Scans previously processed data to find repeated sequences and encodes them as back-references ("repeat M characters from N positions ago")
- Huffman coding: Assigns shorter bit sequences to more frequent values and longer sequences to rarer ones — squeezing the output further
This combination gives PNG better compression ratios and higher quality than GIF.
How Lossy Compression Works
Lossy compression leverages the characteristics of human vision. By discarding information that the human eye is unlikely to notice, it achieves dramatically smaller file sizes.
DCT (Discrete Cosine Transform) — The Heart of JPEG
JPEG divides an image into 8×8 pixel blocks and applies DCT to each:
- Divide the image into 8×8 pixel blocks
- Convert each block from RGB to YCbCr color space (separating luminance from chrominance)
- Apply DCT to transform each block into frequency components (low frequencies = shapes and edges, high frequencies = fine textures)
- Quantize the result: preserve low-frequency components (which the eye is sensitive to) in detail, and coarsely approximate high-frequency components (which the eye doesn't notice as much)
- Apply Huffman coding to compress the quantized values
Higher quality settings preserve more high-frequency detail; lower settings aggressively discard it. When quality is set too low, the block boundaries become visible — a phenomenon known as "blocking artifacts."
Chroma Subsampling
Human vision is significantly more sensitive to changes in brightness (luminance) than to changes in color (chrominance). Chroma subsampling exploits this by keeping the full luminance resolution while reducing the resolution of the color channels.
- 4:4:4: Full color resolution (highest quality, no subsampling)
- 4:2:2: Color resolution halved horizontally
- 4:2:0: Color resolution halved in both directions (most common)
With 4:2:0 subsampling, chrominance data is reduced by 75% with virtually no perceptible quality loss for typical photographic content.
WebP vs. AVIF vs. JPEG XL: An In-Depth Comparison
Technical Background
WebP
Developed by Google in 2010, WebP's lossy mode is based on the VP8 video codec's inter-frame prediction, while its lossless mode uses a variant of DEFLATE. Lossy WebP achieves 25–35% smaller files than equivalent-quality JPEG; lossless WebP is about 26% smaller than PNG.
With 97%+ browser support as of 2024, WebP is the pragmatic choice for most production deployments today.
AVIF
Released in 2019 by the Alliance for Open Media (AOM), AVIF is derived from the AV1 video codec. It achieves an additional 20–35% size reduction over WebP at equivalent quality. It also supports HDR color and wide color gamut, making it particularly valuable for high-end photography and video stills.
The main drawback is slow encoding. Generating AVIF files can be significantly slower than WebP, which matters when processing images at scale. Browser support stands at 93%+ (2024), with Chrome 89+ and Safari 16.0+ providing support.
JPEG XL
Developed with contributions from Google and Cloudflare, JPEG XL (standardized in 2022) has a unique property: it can transcode existing JPEG files into JPEG XL losslessly and convert them back to the original JPEG byte-for-byte. This makes it ideal for migrating legacy JPEG archives without re-encoding.
JPEG XL generally outperforms AVIF in a subset of scenarios, particularly for lossless content. However, Chrome removed support in 2022 (later partially restored), significantly delaying adoption. Safari 18.2 added support, but browser coverage remains limited in 2024.
Format Selection Guide
| Use Case | Recommended | Fallback | Rationale |
|---|---|---|---|
| Photos (general web) | WebP | JPEG | Wide compatibility + good compression |
| Photos (maximum quality) | AVIF | WebP | Best compression at high quality |
| Logos and icons (flat color) | SVG | WebP lossless | Resolution-independent, smallest size |
| Screenshots | WebP lossless | PNG | Preserves text sharpness |
| Animations | WebP | AVIF / GIF | Balance of size and compatibility |
| Email body images | JPEG / PNG | WebP | Some email clients don't support WebP |
Serving Multiple Formats with <picture>
<picture>
<!-- Serve AVIF to browsers that support it -->
<source srcset="image.avif" type="image/avif">
<!-- Fall back to WebP -->
<source srcset="image.webp" type="image/webp">
<!-- Final fallback for all browsers -->
<img src="image.jpg" alt="Product photo" width="800" height="600">
</picture>
The browser selects the first <source> it supports, ensuring optimal format delivery without any JavaScript.
Advanced Responsive Image Patterns
Art Direction
Beyond serving the same image at different sizes, art direction changes the composition or subject based on the device — ensuring the image communicates effectively regardless of screen size.
<picture>
<!-- Mobile: portrait crop focused on the subject -->
<source
media="(max-width: 640px)"
srcset="hero-portrait.webp"
width="640"
height="960"
>
<!-- Tablet: square-ish composition -->
<source
media="(max-width: 1024px)"
srcset="hero-square.webp"
width="1024"
height="768"
>
<!-- Desktop: wide cinematic crop -->
<img
src="hero-wide.webp"
alt="Product hero image"
width="1920"
height="800"
>
</picture>
This is especially effective for e-commerce product images and landing page hero sections, where the subject might be lost in a wide shot on a narrow mobile screen.
Device Pixel Ratio (DPR) Support
Retina displays (DPR 2x) and some Android devices (DPR 3x) need images at 2–3× the CSS pixel dimensions to appear sharp.
<img
src="logo.webp"
srcset="
logo.webp 1x,
logo@2x.webp 2x,
logo@3x.webp 3x
"
alt="Service logo"
width="200"
height="60"
>
Framework-Level Optimization
If you're using a modern framework, much of this is handled automatically.
Next.js Image component:
import Image from 'next/image'
export default function HeroSection() {
return (
<Image
src="/hero.jpg"
alt="Hero image"
width={1200}
height={600}
priority // Above-the-fold LCP element
sizes="(max-width: 768px) 100vw, 50vw"
/>
)
}
Next.js Image handles automatically:
- Conversion to WebP/AVIF on the fly
- Automatic
srcsetgeneration - CLS prevention via
width/height - Priority loading with
fetchpriority - Lazy loading for below-the-fold images
Image Optimization with CDNs
The Role of CDNs in Image Delivery
A CDN (Content Delivery Network) is a globally distributed network of servers. Serving images from a server geographically close to the user minimizes transmission latency — sometimes reducing image load time by hundreds of milliseconds.
Image optimization features by CDN:
| CDN | Auto Format Conversion | On-Demand Resize | Auto Compression |
|---|---|---|---|
| Cloudflare Images | Yes | Yes | Yes |
| Vercel Edge Network | Yes | Yes (Next.js integrated) | Yes |
| Cloudinary | Yes | Yes | Yes |
| Imgix | Yes | Yes | Yes |
| AWS CloudFront + Lambda@Edge | Custom | Custom | Configurable |
Example: Dynamic Image Transformation via URL
Services like Cloudflare Images and Imgix support URL-based transformations, letting you serve perfectly sized images without pre-generating variants:
# Serve at 800px wide, WebP format, quality 80
https://your-domain.com/cdn-cgi/image/width=800,format=webp,quality=80/original/photo.jpg
# Crop to exact dimensions
https://your-domain.com/cdn-cgi/image/width=400,height=300,fit=crop/original/photo.jpg
This eliminates the need to store multiple variants of every image — the CDN generates and caches them on demand.
Cache Control for Images
Maximizing CDN efficiency requires correct cache headers:
# Immutable static assets (content-hashed filenames)
Cache-Control: public, max-age=31536000, immutable
# Dynamic images that might change
Cache-Control: public, max-age=86400, stale-while-revalidate=604800
Including a content hash in the filename (e.g., hero.abc123.webp) ensures that when the image changes, it's treated as a completely new URL — no cache invalidation issues.
Core Web Vitals and Images
LCP (Largest Contentful Paint)
LCP measures how long it takes for the largest content element on the page to become visible. For most pages, that largest element is a hero image.
Good: ≤ 2.5 seconds Needs improvement: > 4.0 seconds
Strategies to improve LCP:
1. Preload the LCP image
<link rel="preload" as="image" href="hero.webp" fetchpriority="high">
2. Set fetchpriority="high"
<img src="hero.webp" fetchpriority="high" alt="Main image" width="1200" height="600">
3. Render the <img> tag in server-side HTML
If the image is injected by client-side JavaScript, the browser won't start downloading it until the script finishes executing. Server-side rendering or static generation ensures the <img> tag is present in the initial HTML, allowing earlier discovery.
4. Serve appropriately sized images
If your hero image displays at 400px wide on mobile but you're serving a 1920px-wide file, you're transferring 5–10× more data than needed. Use srcset and sizes to serve the right dimensions.
CLS (Cumulative Layout Shift)
CLS measures visual stability — specifically, how much the layout jumps around as content loads.
Good: ≤ 0.1 Needs improvement: > 0.25
Common causes and fixes:
Cause 1: Missing image dimensions
<!-- BAD: Browser can't reserve space — will cause layout shift -->
<img src="photo.webp" alt="Photo">
<!-- GOOD: Browser reserves space before the image loads -->
<img src="photo.webp" alt="Photo" width="800" height="600">
Cause 2: Responsive images without aspect-ratio
/* Can cause layout shift if dimensions aren't specified in HTML */
img {
width: 100%;
height: auto;
}
/* Explicitly declare aspect ratio to guarantee space reservation */
img {
width: 100%;
height: auto;
aspect-ratio: 4 / 3;
}
INP (Interaction to Next Paint) and Images
INP replaced FID as a Core Web Vitals metric in March 2024. It measures responsiveness to user interactions.
Decoding large image files can block the main thread, degrading INP. The decoding="async" attribute moves image decoding off the main thread:
<img src="photo.webp" decoding="async" alt="Photo" width="800" height="600">
Caution: don't combine decoding="async" and loading="lazy" on your LCP image — this can significantly delay how long it takes to appear.
A Practical LCP Optimization Checklist
- The LCP image is an
<img>tag in server-rendered HTML (not injected by JavaScript) -
fetchpriority="high"is set on the LCP image - The LCP image does NOT have
loading="lazy" - The image is preloaded via
<link rel="preload"> - The image is served in WebP or AVIF format
- The image dimensions match the actual display size (
srcset+sizes) - Width and height attributes are set to prevent CLS
Tools for Image Optimization
These tools make it easy to start optimizing — no specialized knowledge required, and all processing happens in your browser:
- Image Compressor: Upload any image and compress it to the optimal settings automatically. WebP conversion included. Try the Image Compressor →
- Image Format Converter: Convert between JPEG, PNG, WebP, AVIF, and more. Since conversion happens client-side, your images are never sent to an external server. Try the Image Format Converter →
- Image Resizer: Resize images to match your display dimensions exactly. Handy when preparing multiple sizes for
srcset. Try the Image Resizer →
Conclusion
Image optimization is the highest return-on-investment measure for improving website performance. Simply converting to WebP, setting appropriate sizes, and implementing lazy loading can produce dramatic improvements for most sites.
To go further, adopt AVIF for maximum compression, leverage CDN-level transformation for scalable delivery, and target each Core Web Vitals metric — LCP, CLS, and INP — with specific image-related fixes.
Use your framework's built-in image optimization components and your CDN's automatic format conversion to get most of the benefits with minimal development overhead. Then use PageSpeed Insights to identify specific opportunities and measure your progress after each change.
