We’ve recently published Addy’s Image Optimization book with everything you need to know about images, how to compress, serve and maintain images. Now, shipping with a hand-written personal message, signed by Addy. Jump to the table of contents and get the book right away.
Images are the most popular resource type on the web and are often the largest. Users appreciate high-quality visuals, but care needs to be taken to deliver those hero images, product photos and cat memes as efficiently and effectively as possible.
If you’re optimizing for the Web Vitals, you might be interested to hear that images account for ~42% of the Largest Contentful Paint element for websites. Key user-centric metrics often depend on the size, number, layout, and loading priority of images on the page. This is why a lot of our guidance on performance talks about image optimization.
A tl;dr of recommendations can be found below.
- AVIF is a solid first choice if lossy, low-fidelity compression is acceptable and saving bandwidth is the number one priority. Assuming encode/decode speeds meet your needs.
- WebP is more widely supported and may be used for rendering regular images where advanced features like wide color gamut or text overlays are not required.
- AVIF may not be able to compress non-photographic images as well as PNG or lossless WebP. Compression savings from WebP may be lower than JPEG for high-fidelity lossy compression.
- If both AVIF and WebP are not viable options, consider evaluating MozJPEG (optimize JPEG images), OxiPNG (non-photographic images), or JPEG 2000 (lossy or lossless photographic images).
- Progressive enhancement via
<picture>lets the browser choose the first supported format in the order of preference. This implementation is considerably simplified when using image CDN’s where the Accept Header and content negotiation (e.g. auto-format and quality) can serve the best image.
Why Do We Need Modern Formats?
We have a reasonably wide selection of image formats to choose from when rendering images on the web. The essential difference between image formats is that the image codec used to encode or decode each image type is different. An image codec represents the algorithm used to compress and encode images to a specific file type and decode them for display on the screen.
You can evaluate which image format is suitable for you based on different parameters.
The efficiency of a codec can be mainly measured by how much compression it can achieve. Compression achieved is relevant because the higher the compression, the smaller the file size, and the lower the data required to transfer the image on the network. Smaller file size directly impacts the Largest contentful Paint (LCP) metric for the page as image resources needed by the page get loaded faster.
Ideally, compression should not result in any loss of image data; it should be lossless. Compression formats that result in some loss of image data, thereby reducing the quality of the image, are known as lossy. You may use tools like DSSIM or ssimulacra to measure the structural similarity between images and judge if the loss in quality is acceptable.
- Encode/Decode Speed
Complex compression algorithms may require higher processing power to encode/decode images. This can be complicated by whether encoding is being done ahead of time (static/build) or on-the-fly (on-demand). While encoding may be one-time in the case of static images, the browser still has to decode images before rendering them. A complex decoding process can slow down the rendering of images.
Degree of compression, image quality, and decoding speed are key factors to be considered when comparing image performance for the web. Specific use cases may require image formats that support other features like:
- Software support: An image format may perform very well but is useless if browsers, CDN’s and other image manipulation tools do not recognize it.
- Animation support may be required for some images on the web (e.g., GIF). However, you should ideally replace such images with videos.
- Alpha Transparency: The ability to create images with different opacity levels using the alpha channel. (e.g., PNG images with transparent backgrounds)
- It should support High dynamic range(HDR) imaging and wide color gamut.
- Progressive decoding to load images gradually allows users to get a reasonable preview of the image before it gets refined.
- Depth maps that will enable you to apply effects to the foreground or background of the image.
- Images with multiple overlapping layers, for example, text overlays, borders, and so on.
Tip: When evaluating quality, compression and fine-tuning of modern formats, Squoosh.app’s ability to perform a visual side-by-side comparison is helpful. Zooming in allows you to better appreciate where a format exhibits blockiness or edge-artifacts to reason about trade-offs.
The Old Guards: JPEG And PNG
JPEG has been the most widely supported image format for 25 years. Classic JPEG encoders lead to relatively weak compression, while more modern JPEG encoding efforts (like MozJPEG) improve compression but are not quite as optimal as modern formats. JPEG is also a lossy compression format. While decoding speed for JPEGs is excellent, it lacks other desirable features required of images on modern, eye-catching websites. It does not support transparency in images, animation, depth maps, or overlays.
JPEG works best with photographs, while PNG is its counterpart for other still images. PNG is a lossless format and can support alpha transparency, but the compression achieved, especially for photographs, is considerably low. JPEG and PNG are both used extensively depending on the type of image required.
The target for modern image formats is thus to overcome the limitations of JPEG and PNG by offering better compression and flexibility to support the other features discussed earlier. With this background, let us look at what AVIF and WebP have to offer.
The AV1 image file format (AVIF) is an open-source image format for storing still and animated images. It was released in February 2019 by the Alliance for Open Media (AOMedia). AVIF is the image version of the popular AV1 video format. The goal was to develop a new open-source video coding format that is both state-of-the-art and royalty-free.
AVIF supports very efficient lossy and lossless compression to produce high-quality images after compression AVIF compresses much better than most popular formats on the web today (JPEG, WebP, JPEG 2000, and so on). Images can be up to ten times smaller than JPEGs of similar visual quality. Some tests have shown that AVIF offers a 50% saving in file size compared to JPEG with similar perceptual quality. Note that there can be cases where WebP lossless can be better than AVIF lossless, so do be sure to manually evaluate.
Here, you can see a size comparison between a JPEG image and its corresponding (lossy) AVIF image converted using the Squoosh app:
In addition to superior compression, AVIF also provides the following features:
- AVIF supports animations, live photos, and more through multilayer images stored in image sequences.
- It offers better support for graphical elements, logos, and infographics, where JPEG has limitations.
- It provides better lossless compression than JPEG.
- It supports twelve bits of color depth enabling high dynamic range (HDR) and wide color gamut (WCG) images with a better span of bright and dark tones and a broader range of luminosity.
- It includes support for monochrome images and multichannel images, including transparent images that use the alpha channel.
To better understand the differences in quality and compression offered by the different formats, we can visually compare images and evaluate the differences.
Evaluating Quality And Compression
We will begin our quality evaluation of JPEG, WebP, and AVIF using the default high-quality output settings of Squoosh for each format — intentionally untuned to mimic a new user’s experience with them. As a reminder, you should aim to evaluate the quality configuration and formats that best suit your needs. If you’re short on time, image CDNs automate some of this.
In this first test, encoding a 560KB photo of a sunset (with many textures) produces an image that is visually and perceptually quite similar for each. The output comes in at 289KB (JPEG@q75), 206KB (WebP@q75), and 101KB (AVIF@q30) — up to 81% in compression savings.
Great stuff, but let’s dig deeper.
Various tools exist for comparing the dissimilarity between different image formats (e.g., DSSIM, simulacra). Using these tools, you can approximate the comparable quality setting when evaluating, say, JPEG to WebP or WebP to AVIF. Below are the same images encoded at comparable quality, targeting JPEG’s 70% quality. The output is 323KB (JPEG), 214KB (WebP@q75), and 117KB (AVIF@60) — sizes are a little larger than trusting the defaults, but the compression wins are still significant.
We can also look at lower-quality across each format, which is really where WebP and AVIF shine. Here’s JPEG@q10 (35KB), WebP@q1 (35KB), AVIF@q17 (36KB) — the WebP has significantly fewer blocky artifacts compared to the JPEG, while the AVIF is both less blocky and is sharper on key details in the image.
Note: This sunset is a higher resolution image (
1595), and on 2× screens, the quality could be much lower and still look sharp depending on how users interact with the image (e.g., how much they pinch and zoom).
For a more extreme example of the differences between JPEG and AVIF, we can look at an example from the Kodak dataset (evaluated by Netflix) comparing a JPEG (4:4:4) at 20KB to an AVIF (4:4:4) at 19.8KB. Notice how the JPEG has visible blocky artifacts in the sky and roof. The AVIF is visibly better, containing fewer blocking artifacts. There is, however, a level of texture loss on the roof and some blurriness. It’s still quite impressive, given the overall compression factor is 59x.
Next, let’s evaluate the quality of a beach image with many fine details, textures, and areas of low contrast in the clouds. We will compare the original (at 482KB) to what JPEG, WebP, and AVIF can produce with a 45KB file-size limit (with no advanced tuning) — using Squoosh; this works out at JPEG (MozJPEG) at 50% quality, WebP at 54%, and AVIF at 36%.
The JPEG has blocky artifacts and visible color banding in the clouds and water, while the WebP and AVIF have noticeably less of this blockiness observable. In my opinion, the AVIF offers the overall smoothest experience of all three.
Speaking of textures, we can also perform a similar lower-quality evaluation on a Netflix poster for “The Witcher” (targeting 36KB). Notice the blockiness in the clouds for the JPEG and some blurriness around the red text for WebP (which only supports 4:2:0 chroma subsampling without workarounds). The AVIF looks best, followed by the WebP.
Finally, let’s look at a photo with a lot more text elements than previous images — a poster. When we go down to lower qualities and target a reasonably small size (25KB), we can observe that the JPEG has strong color banding and halos around the text. There are clear blocky artifacts around the edges. The WebP avoids an amount of the blockiness, looking incrementally better. The AVIF preserves the sharp edges a little better than either JPEG or WebP, producing a smooth image.
AVIF Tooling And Support
Since its release in 2019, the support for AVIF has increased considerably. While there was no direct method to create or view AVIF files earlier, you can easily do so now with the open-source utilities available.
AVIF Images In The Browser
AVIF was introduced on the desktop version of Chrome in August 2020 with Chrome 85. It is also supported on Chrome for Android, Opera and Firefox for desktop, and Opera for Android.
To include an AVIF image on your page, you can add it as an image element. However, browsers that do not support AVIF cannot render this image.
<img src="/images/sky.avif" width="360" height="240" alt="a beautiful sky">
A workaround to ensure that at least one supported image format is delivered to all browsers is to apply AVIF as a progressive enhancement. There are two ways to do this.
- Using The
<picture>allows browsers to skip images they do not recognize, you can include images in your order of preference. The browser selects the first one it supports.
<picture> <source srcset="img/photo.avif" type="image/avif"> <source srcset="img/photo.webp" type="image/webp"> <img src="img/photo.jpg" alt="Description" width="360" height="240"> </picture>
- Using Content Negotiation
Content negotiation allows the server to serve different resource formats based on what is supported by the browser. Browsers that support a specific format can announce it by adding the format to their Accept Request Header. E.g., the Accept Request Header for images in Chrome is:
The code to check if AVIF is supported in the fetch event handler can look something like this:
const hdrAccept = event.request.headers.get("accept");
const sendAVIF = /image\/avif/.test(hdrAccept);
You can use this value to serve AVIF or any other default format to the client.
Creating the markup for progressive enhancement can be daunting. Image CDN’s offer the option to automatically serve the best format suitable to the client. However, if you are not using an image CDN, you can consider using a tool like just-gimme-an-img. This tool can generate the markup for the picture element for a given image with different formats and widths. It also creates the images corresponding to the markup using Squoosh entirely client-side. Note: encoding multiple formats can take a while using it, so you might want to grab a coffee while you wait.
Note: Image CDNs are mentioned a few times in this article. CDN servers are often located closer to users than origin servers and can have a shorter round-trip times (RTT), improving network latency. That said, serving from a different origin can add round-trips and impact performance gains. This may be fine if the CDN is serving other site content, but when in doubt, experiment and measure.
Encode And Decode AVIF Files
Several open-source projects provide different methods to encode/decode AVIF files:
Libaom is the open-source encoder and decoder maintained by AOMedia, the creators of AVIF. The library is continuously updated with new optimizations that aim to reduce the cost of encoding AVIF, especially for frequently loaded or high-priority images. Libavif is an open-source muxer and parser for AVIF used in Chrome for decoding AVIF images. You can use libavif with libaom to create AVIF files from original uncompressed images or transcode them from other formats. There is also Libheif, a popular AVIF/HEIF encoder/decoder and Cavif. Thanks to Ben Morss, libgd supports AVIF and is also coming to PHP in November.
- Web Apps And Desktop Apps
Squoosh, a web app that lets you use different image compressors, also supports AVIF, making it relatively straightforward to convert and create
.aviffiles online. On desktop, GIMP supports AVIF exporting. ImageMagick and Paint.net also support AVIF while Photoshop community plugins for AVIF are also available.
- AVIF.js is an AVIF polyfill for browsers that do not support AVIF yet. It uses Service Worker API to intercept the fetch event and decode AVIF files.
- Avif.io is another web utility that can convert files from different image types to AVIF on the client-side. It calls Rust code in the browser using a WebWorker. The converter library is compiled to WASM using wasm-pack.
- Sharp is a Node.js module that can convert large images in standard formats to smaller web-friendly images, including AVIF images.
Image conversion or transformation utilities support the AVIF format. You can use MP4Box to create and decode AVIF files.
- In Code
go-avifimplements an AVIF encoder for Go using
libaom. It comes with a utility called
avifwhich can encode JPEG or PNG files to AVIF.
AVIF And Performance
AVIF can reduce the file size of images due to better compression. As a result, AVIF files download faster and consume lower bandwidth. This can potentially improve performance by reducing the time to load images.
Lighthouse-best practices audit now considers that AVIF image compression can bring significant improvements. It collects all the BMP, JPEG, and PNG images on the page, converts them to WebP and estimates the AVIF file size. This estimate helps Lighthouse report the potential savings under the “Serve images in next-gen formats” section.