Converting a Directory of PNGs or JPGs to WebP via the Command Line

Reading Time: 2 minutes

If you find yourself in need of easily converting a full directory of images, say a web sequence of about 100 PNGs, to the webp format then you’ve come to the right place!

First you’ll need to install ImageMagick.

For the quickest installation, I’d recommend using Homebrew. You can check out the ImageMagick Download page for other installation methods.

brew install imagemagick

Next, if not already installed, you’ll need to install the Ghostscript fonts ImageMagick uses.

brew install ghostscript

Now to confirm things are working you can run:

// creates a logo.gif file in the current directory
magick logo: logo.gif

// outputs information about logo.gif
identify logo.gif

Creating a Bash Script to run

Next we’ll create a bash script that can be run from the command line with convert-webp.sh and will take an input directory or use the current directory and output to a webp directory or some other specified directory.

Create a file named convert-webp.sh in your preferred directory. For examples ~/scripts.

Add this code.

#!/bin/bash

# Prompt the user for the input directory
read -p "Enter the input directory (leave blank for current directory): " input_dir

# Use the current directory if input_dir is left blank
if [ -z "$input_dir" ]; then
    input_dir="."
fi

# Prompt the user for the output directory
read -p "Enter the output directory (leave blank for 'webp'): " output_dir

# Use "webp" as the default output directory if output_dir is left blank
if [ -z "$output_dir" ]; then
    output_dir="webp"
fi

# Create the output directory if it doesn't exist
mkdir -p "$output_dir"

# Function to convert images to WEBP format
convert_to_webp() {
    for file in "$input_dir"/*.$1; do
        # Check if there are no matching files
        [ -e "$file" ] || continue
        # Extract the filename without the extension
        filename=$(basename "$file" .$1)
        # Convert the image file to WEBP format
        magick "$file" "$output_dir/$filename.webp"
        # Print the new filename
        echo "Converted $file to $output_dir/$filename.webp"
    done
}

# Convert PNG files
convert_to_webp "png"

# Convert JPG files
convert_to_webp "jpg"

echo "Conversion complete!"

In order to be able to run this you’ll then need to go to the directory you saved the file in your terminal.

cd ~/scripts

To make the script executable, you need to use the chmod command to set the appropriate permissions. You can run the following command in your terminal:

chmod +x convert-webp.sh

This command adds the execute permission to the script, allowing it to be run as a program.

Then so you can run the script anywhere move the script to a directory in your PATH line /bin with:

sudo mv convert-webp.sh /usr/local/bin/

Now you can run convert-webp.sh in the directory with your PNG or JPG images and they’ll be automatically converted to webp.

Pin It on Pinterest