5

Quick script to convert JPEG/PNG images to WebP and AVIF

 7 months ago
source link: https://pawelgrzybek.com/quick-script-to-convert-jpeg-png-images-to-webp-and-avif/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Quick script to convert JPEG/PNG images to WebP and AVIF

Published: 2024.01.21 · 2 minutes read

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
A pretty cool view from one of the Greek islands
JPEG: 196kb, WebP: 88kb, AVIF: 61kb

Did you like it? Please share it with your friends or get me a beer coffee. Thanks!

Leave a comment#

Name:
Website (optional):
GitHub (optional):
Comment:

👆 you can use Markdown here

Save my data for the next time I comment

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK