site logo

Use AVIF Images in your webpage with JPEG Fallback

AVIF is the next big thing in image format. It is a lossy/lossless image format that originates from the video codec AV1. In other words, AVIF to AV1 is like HEIF to HEVC, except AVIF is open, royalty-free, and pushed by a lot of big companies. Just like AV1, AVIF has a bunch of modern features. HDR, 10-bit color depth, etc.

In a webpage, AVIF means saving bandwidth and higher compression ration. All royalty free, just like JPEG!

Great, how do I convert my image to AVIF?

If your source image is lossy-compressed (say JPEG), don’t. Compressing something twice usually makes things worse.

If you have a PNG image, the Rustlang tool cavif seems good.

So how to use AVIF in HTML?

On supported browsers, it is as easy as an

<img src="your_pic.avif" alt="My beautiful AVIF pic" />

But wait, what browsers are supported? A lot, but not enough. Recent Chrome has full AVIF support. Firefox does have AVIF, but it is hidden behind a config flag. Safari hates royalty-free codes, and does not support AVIF at all.

So we need to implement some good old JPEG fallback. Fortunately, HTML5’s <picture> tag made this easy.

  <!--This is the optional AVIF image-->
  <source type="image/avif" srcset="i-like-avif.avif">
  <!--This is the fallback JPEG image-->
  <img alt="Did that not work?" src="jpeg-is-gold.jpg">

It really is that easy. Now you just need to convert all images to AVIF to save a bunch of bandwidth!

Personal view

To be honest, I feel like AVIF is not designed specifically for image compression. Just like HEIF, it originates from a video codec. But it is infinitely better than JPEG, which is widely used even in 2021.

So, AV1 looks like a win-win solution, both to video codec and to image compression.