Quick script to convert JPEG/PNG images to WebP and AVIF
Browser support for modern image formats like WebP and AVIF is excellent, so you should use them to take advantage of their bandwidth savings. By taking a little care and preparing these image formats for my articles, I am saving you around 60% of the data compared to JPEG equivalents. You are welcome!
Modern frameworks often come equipped with the tooling that can handle format conversion for you. A plugin for your favourite tool may already exist if they are not built-in. Next.js <Image> component and Gatsby Image plugin come built-in. The @sveltejs/enhanced-img for Svelte fans and @11ty/eleventy-img for Eleventy users are just one npm install away.
Hugo, which I use to build this website, supports WebP but cannot generate AVIF images. Because of this limitation of the Hugo Fit method, I do the image conversion myself using a simple script I wanted to share with you today. It is a fish-shell script, but it should be simple to replicate it in bash or zsh. It relies on three external dependencies: webp, avif and imageoptim-cli.
function optim
for file in $argv
set filePath (realpath $file)
set filePathNoExtension (string split -r -m 1 . -- $filePath)[1]
set filePathWebp $filePathNoExtension.webp
cwebp -quiet $filePath -o $filePathWebp
avif --input="$filePath"
imageoptim --no-stats $filePath
end
end
My GitHub has a more advanced version with fancy logging and safety nets. Here is an example of how you invoke it. I am also attaching a picture generated by the script above with a detailed description of size differences between different formats. I hope you found it helpful!
optim one.jpg two.jpg three.png
