How to convert images to AVIF in NodeJS
What is AVIF and why should I be using it?
AVIF is the latest next-gen image compression format. It offers significant file size reduction for images compared with JPEG ( ~50% ) or WebP ( ~20% ). Chrome recently shipped support for
AVIF in Chrome 85 and it can be enabled in
Firefox via the image.avif.enabled
flag in about:config
.
Take a look at this blog post published by Netflix if you're looking for a more in-depth comparison.
How can I convert my images to AVIF?
Squoosh recently shipped support for AVIF if you don't mind manually converting your images.
If you're looking for a more automated method, you could try using Sharp. Sharp offers support for AVIF although it is currently experimental.
Unfortunately, Sharp's prebuilt binaries do not support AVIF, so you will have to compile
libvips
with support for libheif
before you can start taking advantage of this "experimental" feature.
To simplify this process I created a Dockerfile that I'm using in sharp-image-proxy.
If you aren't familiar with Docker, I suggest you read my post: Introduction to Docker.
Once you have libvips
installed and compiled with support for
libheif
you can start using the Sharp API.
Here's an example of how you can convert a png to avif:
import * as sharp from 'sharp';
sharp('input.png')
.toFormat('heif', { quality: 30, compression: 'av1' })
.toFile('output.avif')
.then(info => console.log(info));