Convert PNG or JPG to WEBP via the command-line on macOS

2025-01-21

tl;dr

[brew install webp &&] file_path=./images/img1 && cwebp "$file_path.png" -o "$file_path.webp"

Lack of native webp support on macOS

webp is generally accepted as the modern file format for images on the internet. However out of the box support on macOS is poor: the built-in Preview app doesn't allow you to export images as .webp and you can't save screenshots as webp by default.

Instead, you're left with a bunch of .png files that are not optimised for the internet.

Let's see how we can sort this out via the command line.

Installing webp

First we'll need to install the webp software. One easy way to get this done on macOS is via homebrew. for the purpose of this guide we're going to assume you have homebrew set up. If you don't more can be found on that here.

brew install webp.

Converting The Images

Single file

You can reference the path and set an output (-o)

cwebp ~\images\img1.png -o ~\images\img1.webp

This is pretty straight forward but it's also more verbose than we'd like (assuming you don't want to rename the file).

It can be shortened to this:

file_path=./images/img1 && cwebp "$file_path.png" -o "$file_path.webp"

Multiple Files

But what about if we have a lot to do?

Instead, you can loop through a folder and update all of those in one go:

for file in ./public/images/*; do [[ $file =~ \.(jpg|png)$ ]] && cwebp "$file" -o "${file%.*}.webp"; done

And there you go...

References

https://www.delasign.com/blog/convert-jpeg-jpg-png-to-webp-macos/ https://developers.google.com/speed/webp/docs/cwebp https://formulae.brew.sh/formula/webp

Found This Useful?

If you have any questions you'd like to ask me about this post, feel free to reach me on Twitter or Github.

If you found this post useful and would like to show you're appreciation, feel free to send me a tip via the Brave Browser.