Batch Converting PNG files to WEBP

Recently, I was tasked with taking a large directory of png images and converting them to webp format

It turns out Affinity Photo does not support webp, so this ended up being a slightly tricky compared to converting other image formats. I'm writing this post to document the process to save myself and others time in the future.

Installing CWebP

There is a command line app that can be used to convert images to webp format. This app is called cwebp and can be installed by downloading it directly from Google

Or, if you are using a mac, using Homebrew.

Running CWebP

You can use cwebp to convert an image like this

cwebp inout.png -o image.webp

Where input.png is an image file (other types such as jpg are also supported) and image.webp is the output file.

Batch Converting A Directory Of Files

I had a directory containing many files that needed to be converted, so I whipped up a simple bash script to convert an entire directory with a single command. Note that this script expects you to be in the correct directory before it runs.

for file in ./*; 
do 
  cwebp $file -o `echo $file | sed 's/\.\///g' | sed 's/\.png/\.webp/g'` ; 
done

This script runs once for every file in the current directory converting "{ filename }.png" to "{ filename }.webp". We pipe the name of the file through sed to remove the prefix and extension

./1.png

will become

./1.webp

A Standalone converting function

This BASH function is also pretty useful. It assumes that you are in the directory with the image and that the image you are converting is a png, but you could easily modify it to suit your needs.

convert () { cwebp $1.png -o $1.webp; }

Assuming you had an image called hello.png, You could use the method like this

cd /path/to/image 
convert hello

Afterwards there will now be a new "hello.webp" file in the directory

Very handy! Hope this helps someone else out there too.

Similar Blog Posts

A Simple Trait Validation Technique

I show off a common Trait issue and what I do to work around it

How I nearly accidentally automated my entire department out of a job

A story of an internship I did with a governmenmental IT Dept

Some Tips For Migrating To The VueJS Composition API

Some tips on using the new Composition API for VueJS 3