DEV Community

Adam LaCombe
Adam LaCombe

Posted on • Originally published at adamlacombe.com on

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));


Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
henrihelvetica profile image
Henri Helvetica

Thx for the post. We're clearly going to a lossy AVIF. Have you tested png-8 and png-24 separately? No issues w/ the transparencies either?? Super curious has avif will come in diff bit depths and sub sampling as well.

Collapse
 
adamlacombe profile image
Adam LaCombe

I've only tested png-24/png-32. I had issues with transparency in the beginning (if I remember right - it was an issue with libheif). The issue had been patched but unreleased, so I ended up cloning libheif while I wait for their the next release.