UI Drafter
Blog

Convert to AVIF Programmatically

October 2, 2020
June 4, 2021 (Updated)
Eric Fortis

This shell script converts JPG and PNG images into AVIF and WebP using libavif and Google's WebP encoder.

# macOS
brew install joedrago/repo/avifenc webp

# Arch Linux
sudo pacman -S libavif webp

For AVIF, it uses a compression of min = 25 and max = 35, which works well for UI Drafter's screenshots (images with text and sharp edges). Besides smaller file sizes, they make optically better images than cwebp. No artifacts, sharper, and more accurate colors.

jpg 132 kB
webp 29 kB
avif 22 kB
#!/bin/sh
set -o noglob
IFS=$'\n'

images=$(find ~/imgs -type f -name *.png -o -name *.jpg)

for img in $images; do
  avif_out=$img.avif
  webp_out=$img.webp

  if [ ! -f $avif_out ]; then
    avifenc --speed 0 --min 25 --max 35 $img $avif_out
  fi

  if [ ! -f $webp_out ]; then
    cwebp $img -o $webp_out
  fi
done

The images end up with the original extension plus the modern one (e.g. foo.png.avif), because I need those file names to Conditionally Serve the Optimal Image Format with Nginx.

June 4, 2021 Update

It's worth mentioning another tool: squoosh-cli. The original extension is prepended using --suffix.

npm install -g @squoosh/cli

squoosh-cli --avif auto --suffix '.png' foo.png
# Outputs: foo.png.avif

Sponsored by: