Back to blog
Web Development

How to Compress Images for Faster Website Loading

Compress website images the right way: resize to display size, convert to WebP or AVIF, tune quality, and automate it all for faster page loading times.

AdminOctober 19, 202612 min read2 views
How to Compress Images for Faster Website Loading

How to Compress Images for Faster Website Loading

On most websites I audit, images are the heaviest thing on the page, and the fix rarely requires a new tool. It requires three decisions made consistently: the right format, the right dimensions, and the right quality setting. Image compression is the process of reducing an image file's size by removing redundant or less noticeable data, either without any visible change (lossless) or with a controlled, usually imperceptible quality trade-off (lossy). Done well, it is the fastest way to make pages load quicker without touching a line of application logic.

Quick Answer: To compress images for faster loading, resize each image to the largest size it actually displays, convert photos to WebP or AVIF with lossy quality around 75 to 85, strip metadata, and serve responsive sizes with srcset. Lazy-load images below the fold, but never the main hero image.

What Image Compression Means and Why It Speeds Up Pages

Image compression speeds up pages by reducing the number of bytes the browser has to download before it can display your content. Fewer bytes means shorter download time, especially on mobile networks, and it often directly improves Largest Contentful Paint, because the largest element on many pages is a hero image or product photo. If you are working on overall page speed work, images are usually the first and cheapest place to find gains.

Two compression types matter. Lossless compression reorganizes data more efficiently so the decoded image is pixel-identical to the original; it suits logos, icons, screenshots, and graphics with sharp edges and flat colors. Lossy compression discards detail the human eye is unlikely to notice, such as subtle color variations in a photograph; it produces dramatically smaller files and is the right choice for nearly all photographs on the web.

Compression is only one of three levers, and it is the least important of the three if the other two are wrong. The first lever is dimensions: a 4000-pixel-wide photo displayed in an 800-pixel container wastes most of its bytes no matter how well it is compressed. The second is format: modern formats such as WebP and AVIF encode the same visual quality in fewer bytes than JPEG and PNG. The third is the quality setting itself. Get dimensions and format right, and the quality setting becomes fine-tuning.

It also helps to know the formats by their strengths. JPEG is universal and good for photos. PNG is lossless and supports transparency but is heavy for photos. WebP, developed by Google, supports both lossy and lossless modes plus transparency; Google's own documentation states that lossless WebP images are 26% smaller than PNGs and lossy WebP images are 25 to 34% smaller than comparable JPEGs. AVIF, based on the AV1 video codec, often compresses further than WebP at the cost of slower encoding. SVG is a vector format and is ideal for logos and icons.

Step-by-Step: How to Compress Images the Right Way

A repeatable process matters more than any single tool. This is the workflow I use whether a site has twenty images or twenty thousand.

  1. Audit what you already serve. Run PageSpeed Insights or the Lighthouse panel in Chrome DevTools and look for "Properly size images" and "Serve images in next-gen formats." The Network panel, filtered by Img and sorted by size, shows your heaviest offenders immediately.
  2. Determine display sizes. For each image slot in your layout, note the largest rendered width across breakpoints. Multiply by two for high-density screens if sharpness matters, but rarely go beyond that.
  3. Resize before compressing. Export or generate images at those widths. Typical responsive sets include widths such as 480, 800, 1200, and 1600 pixels for full-width images.
  4. Choose the format by content type. Photos to WebP or AVIF lossy. Screenshots and flat graphics to WebP lossless or PNG. Logos and icons to SVG.
  5. Set a quality level and compare visually. Start lossy WebP around 75 to 85 and AVIF somewhat lower, since AVIF quality scales differ. Compare side by side at actual display size, not zoomed in to 400%.
  6. Strip metadata. Remove EXIF data such as camera details and GPS coordinates. It adds bytes and can leak private location information.
  7. Serve responsively. Use srcset and sizes so each device downloads the smallest adequate file, and a <picture> element if you need format fallbacks.
  8. Set explicit dimensions. Add width and height attributes so the browser reserves space and avoids layout shift.
  9. Load intelligently. Add loading="lazy" to below-the-fold images and fetchpriority="high" to the hero image.
  10. Automate it. Move compression into your build pipeline, CMS upload hook, or an image CDN so nobody has to remember these steps.

Tools that handle these steps well include Squoosh for one-off manual comparisons, the sharp library or libvips for Node.js build pipelines, cwebp and avifenc command-line encoders, and ImageMagick for batch jobs. Most modern frameworks also include image components, such as the Next.js Image component, that resize and convert on demand.

Image Formats Compared for Web Performance

Choosing the right format is the decision that most affects final file size. This comparison reflects how each format behaves in practice on production websites.

FormatCompression typeBest used forMain trade-off
JPEGLossyPhotos where maximum compatibility is required, such as emailLarger than WebP and AVIF at equal quality; no transparency
PNGLosslessScreenshots and graphics needing exact pixels or transparencyVery heavy for photographs
WebPLossy and losslessDefault choice for most web photos and graphicsSlightly less efficient than AVIF on photos
AVIFLossy and losslessLarge hero images and photo-heavy pagesSlower to encode; tune quality carefully to avoid smoothing fine detail
SVGVector (text-based)Logos, icons, simple illustrationsUnsuitable for photos; complex SVGs can become large

All current versions of the major browsers support both WebP and AVIF, which means the old argument for JPEG-only delivery mostly applies to email clients and very old devices. If you need a fallback, the <picture> element lets the browser pick the first format it supports.

What Years of Image Audits Reveal About Real-World Savings

The biggest savings almost never come from squeezing quality settings; they come from fixing oversized dimensions. This is practitioner analysis from repeated audits rather than a published dataset, but it holds across CMS sites, ecommerce stores, and custom builds.

The typical pattern looks like this: a content editor uploads a photo straight from a phone or stock site at several thousand pixels wide, the theme displays it at a fraction of that, and the CMS serves the original file. Resizing that one image to its displayed width often cuts more bytes than every other optimization on the page combined. Format conversion then delivers a second, smaller round of savings, and quality tuning a third, smaller still.

The second pattern is that images degrade over time even on well-built sites. Developers set up a perfect pipeline at launch, then a marketing team adds a slider through a page builder, a blog plugin bypasses the image component, or an editor pastes a PNG screenshot of a photo. This is why image weight belongs in ongoing monitoring, alongside other common developer SEO pitfalls such as missing alt text and blocked image directories that quietly undermine both speed and image search visibility.

The third pattern concerns perceived quality. Teams often set quality to 95 or even 100 out of caution. At normal viewing size, visitors rarely notice a difference between a well-encoded lossy image at a moderate quality setting and one at maximum quality, while the file size difference can be large. The right way to settle the debate is a blind side-by-side comparison at real display size on a phone, not a pixel-peeping session on a large monitor.

Finally, compression interacts with caching. A well-compressed image served with long cache headers and a content-hashed filename only downloads once per visitor. A poorly cached image re-downloads on every visit, multiplying the cost of whatever bytes it carries.

Common Image Compression Mistakes and How to Avoid Them

Most image performance problems come from a handful of repeat mistakes. Each has a simple preventive fix.

  • Compressing without resizing. A heavily compressed 5000-pixel image is still far heavier than needed. Always resize to display dimensions first.
  • Using PNG for photographs. PNG's lossless encoding makes photos enormous. Convert photos to lossy WebP or AVIF and reserve PNG for graphics that truly need it.
  • Lazy-loading the hero image. It delays the largest visible element and worsens LCP. Load it eagerly with high fetch priority.
  • Re-compressing already compressed files. Each lossy save compounds artifacts. Keep high-quality masters and generate web versions from them every time.
  • Missing width and height attributes. Without reserved space, images push content down as they load and cause layout shift. Always declare dimensions or an aspect ratio.
  • Serving one size to all devices. A desktop-sized image on a small phone wastes data. Use srcset and accurate sizes values.
  • Using raster images for icons. Icon sets as PNG sprites or icon fonts add weight and blur on high-density screens. Use inline or external SVG.

Implementation Walkthrough: An Automated Pipeline for a Content Site

Here is a practical setup for a content-heavy site where editors upload images daily and nobody should have to think about compression.

Storage of masters. Editors upload original images to a media library or object storage. These masters are never served directly; they are the source for every derived version, which avoids repeated lossy re-encoding.

Derivative generation. On upload, a server function using the sharp library generates WebP and AVIF versions at a fixed set of widths, strips metadata, and stores each derivative with a content hash in the filename. A typical configuration encodes WebP around quality 80 and AVIF around quality 50 to 60, then the team spot-checks a sample visually and adjusts once rather than per image.

Markup. The site's image component outputs a <picture> element with an AVIF source, a WebP source, and a JPEG fallback, each with a srcset covering the generated widths. The sizes attribute matches the actual CSS layout, for example full width on mobile and a fixed column width on desktop. Width and height attributes come from the master's aspect ratio.

Loading rules. The component accepts a priority flag. The first image in an article or the hero on a landing page receives eager loading and high fetch priority; every other image gets lazy loading.

Caching. Derivatives are served from a CDN with long-lived immutable cache headers, safe because filenames change whenever content changes.

Guardrails. A CI check flags any committed image above a size budget, and a monthly Lighthouse run on key templates catches regressions. Use this checklist when reviewing a new template:

  • Hero image eager, high priority, correctly sized for mobile
  • All other images lazy-loaded with declared dimensions
  • Modern formats served with a fallback where needed
  • Sizes attribute matches the real layout at each breakpoint
  • Descriptive alt text present on meaningful images

Key Takeaways

  • Resizing images to their actual display dimensions usually saves more bytes than any quality setting or format change.
  • WebP is the safest default for web photos, while AVIF can compress large hero images further at the cost of slower encoding.
  • Lazy loading helps below-the-fold images but harms LCP when applied to the main hero image.
  • Keeping uncompressed masters and generating derivatives automatically prevents quality loss from repeated lossy saves.
  • Declaring width and height on every image is a compression-adjacent habit that prevents layout shift for free.

Frequently Asked Questions

What is the best image format for website speed?

For most websites, WebP is the best all-round format because it offers strong compression, transparency support, and broad browser support. AVIF can produce even smaller files for large photographs. Use SVG for logos and icons, and keep JPEG or PNG only as fallbacks or for cases like email where modern formats are not supported.

What quality setting should I use when compressing images?

A lossy WebP quality between about 75 and 85 works well for most photographs, while AVIF typically looks comparable at lower numeric settings because its scale differs. Do not rely on numbers alone. Compare compressed and original images side by side at their real display size on a phone and pick the lowest setting that looks identical.

Does compressing images reduce their quality?

Lossless compression never reduces quality because the decoded image is identical to the original. Lossy compression removes some data, but at sensible settings the difference is usually invisible at normal viewing size. Quality loss becomes noticeable only when settings are too aggressive or when an image is repeatedly re-saved in a lossy format.

Should I lazy-load all images on my website?

No, you should lazy-load only images that appear below the fold. The hero image or any image visible on initial load should load eagerly, ideally with high fetch priority, because lazy loading it delays Largest Contentful Paint. Native lazy loading with the loading attribute is supported in all modern browsers and needs no JavaScript library.

How do I compress images in bulk?

For bulk compression, use a scripted tool rather than manual exports. The sharp library for Node.js, ImageMagick, or command-line encoders like cwebp and avifenc can resize and convert entire folders. For ongoing needs, automate compression in your build process, CMS upload hooks, or an image CDN so new uploads are optimized automatically.

Do image file sizes affect SEO?

Image file size affects SEO indirectly through page speed and Core Web Vitals, particularly Largest Contentful Paint. Heavy images slow pages, which can hurt user experience and conversions. Images also rank in Google Images, where descriptive filenames, alt text, and fast loading help them get discovered and displayed to searchers.

Conclusion

The single most important image decision is to resize before you compress, then let automation handle format and quality every time. A pipeline that generates correctly sized WebP and AVIF versions from untouched masters, served with responsive markup and sensible loading priorities, removes image weight as a recurring problem instead of a quarterly cleanup. Once your images are lean, make sure the rest of each page is ready for search by running through a launch-ready on-page checklist before publishing.

Chat on WhatsApp