Skip to content

Bulk Image Conversion to WebP with a Simple Zsh Function

Posted on:August 8, 2025

In today’s web development landscape, image optimisation is crucial for performance. WebP format offers superior compression compared to traditional formats like JPEG and PNG, often reducing file sizes by 25-50% while maintaining similar quality. After repeatedly converting images manually, I created a simple Zsh function to automate the process.

Prerequisites

First, you’ll need ImageMagick installed on your system:

macOS (with Homebrew):

brew install imagemagick

Ubuntu/Debian:

sudo apt-get install imagemagick

The Simple Solution

Here’s the function I use daily, simple, effective, and gets the job done:

convert_to_webp() {
  setopt null_glob  # prevent 'no matches found' errors
  for ext in jpg jpeg png; do
    for f in *.$ext; do
      [ -e "$f" ] || continue
      output="${f%.*}.webp"
      magick "$f" -quality 80 -define webp:method=6 "$output"
      echo "Converted: $f -> $output"
    done
  done
  unsetopt null_glob  # clean up after ourselves
}

That’s it. No complicated options, no verbose output, just converts every JPG, JPEG, and PNG in the current directory to WebP with sensible defaults.

Why These Defaults?

Usage

Simply navigate to your image directory and run:

convert_to_webp

Example output:

Converted: photo1.jpg -> photo1.webp
Converted: screenshot.png -> screenshot.webp
Converted: banner.jpeg -> banner.webp

File Size Comparisons

Here are some real-world examples of the savings you can expect:

Original FormatOriginal SizeWebP SizeSavings
PNG (screenshot)2.4 MB1.1 MB54%
JPEG (photo)3.8 MB2.1 MB45%
PNG (icon)145 KB32 KB78%
JPEG (web image)856 KB524 KB39%

The savings vary depending on the image content, screenshots and graphics with large solid areas compress exceptionally well, while detailed photos see lower but still significant reductions.

Adding to Your Dotfiles

For my dotfiles setup, I added the function to my zsh/functions file, then it’s automatically available in any new shell session.