Blog Post Feature Images as AVIF (with JPEG Fallback)

AVIF files are images available to be shown on the web, made using the AV1 codec. They offer superiour compression and quality when compared with jpeg files and can be a good choice for display ’nice-looking’ pictures on your site.

In this post we look at how you can start using them with Hugo. We originally made the avif files using Gimp, but there are online converters available.

To begin with, this is how we define the images we want to use for the blog post. We specify both a feature image, and a 2x image.

1
2
3
4
5
6
---
title: "Blog Post Feature Images as AVIF (with JPEG Fallback)"
url: /add-avif-feature-image/
featured_image: /img/2020/hugos-parachute.jpg
retina_image: /img/2020/hugos-parachute@2x.jpg
---

single.html

Within your theme, you can then use the <picture> element to display avif images - if the browser supports it - or fallback to jpeg. Because we’re going to be rolling this feature out slowly, some posts might not have avif files for them so we check to make sure the file is available first.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
{{ if .Params.featured_image }}
    <div class="banner-image">
        <picture>
            {{ if fileExists (replace .Params.featured_image "jpg" "avif") }}
                <source type="image/avif" 
                        srcset="{{ replace .Params.featured_image "jpg" "avif" }}, {{ replace .Params.retina_image "jpg" "avif" }} 2x"
                        width="800"
                        height="150"
                        alt="{{ .Title }}">
            {{ end }}
            <img src="{{ .Params.featured_image }}" 
                 srcset="{{ .Params.featured_image }} 1x, {{ .Params.retina_image }} 2x"
                 width="800"
                 height="150"
                 alt="{{ .Title }}">
          </picture>
    </div>
{{ end }}

In our picture tag, we’re also assuming that the avif file has the same name as the jpeg fallback - as all we do is replace the file extension in the name.