Post

Using WebP images for this blog

How I have converted all the images of this blog to WebP instead of PNG or JPEG.

Using WebP images for this blog

I have recently seen many posts about websites good practices measured by tools like Lighthouse in Chrome-based browsers. I regularly audit this blog and I have improved its score by converting all the images into WebP.
Let’s see quickly how you can do this for your website as well.

What is WebP and how to get started

WebP is an image format developed by Google, now open source and supported by all major browsers. Using WebP instead of PNG/JPEG promises better compression, performance and SEO (check the links for real information about this 🤗).

Google ships utilities to convert images from and to WebP, you’ll find installation instructions here. As a lazy Linux user (WSL2 with Windows 11), I have used Homebrew with the command brew install webp.

The utility we are going to use is cwebp, to convert images from PNG/JPEG to WebP.

What to do once the tools are installed ?

Alright, so using this cwebp tool is not rocket science, as shown in the docs it’s pretty easy to convert a single image.
But this blog has been running for a few years now so in my case I had more than hundred images spread across dozens of folders to convert. How to achieve that ?

Well, it requires some Bash knowledge I didn’t had at the time. Enough talking, let me spare you some googling time and share the one-liner I came up with:

1
for i in **/*.png; do cwebp "$i" -o "${i/png/webp}"; rm "$i"; done

Running this from the assets folder of my blog converts all the PNG images to WebP, keeps the same folder and file name as the originals, uses the .webp file extension, and removes the originals.
Replace png by jpeg to do the same thing for JPEG files:

1
for i in **/*.jpeg; do cwebp "$i" -o "${i/jpeg/webp}"; rm "$i"; done

Then a few search and replace across the markdown files and the job is done !

Keeping on converting everyday

Now that the historical images have been converted, to convert new images easily I needed an alias instead of searching the above command in my history.
For a reason I don’t remember, using the one-liner directly as an alias did not work, so I ended up putting this in my ~/.zshrc file:

1
2
3
4
5
6
7
8
function png2webp() {
  for i in **/*.png; do
    cwebp "$i" -o "${i/png/webp}"
    rm "$i"
  done
}

alias png2webp='png2webp'

And I use the png2webp alias to convert images before publishing a new post.

Wrapping-up

That’s it for this post, a quick article to share some commands to follow the trend of image format for your website. Regarding my score in Lighthouse, it was slightly better after the conversion to WebP, but not that much honestly (probably because my PNGs were already optimized using tinify).

There are still room for improvement on this website, I will continue to improve my score and encourage you to do so 🤓

This post is licensed under CC BY 4.0 by the author.