Shell script
Convert to AVIF Programmatically

by Eric Fortis

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

# macOS
brew install libavif 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 Rig’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.

png 250 kB
webp 112 kB
avif 72 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 [ $img -nt $avif_out ]; then
    avifenc --speed 0 --min 25 --max 35 $img $avif_out
  fi

  if [ $img -nt $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.

Sponsored by: