Skip to content

Managing Image Assets with WebP

Large image assets are a massive drag on website performance.

2 min read
WebP
Image
Conversion
Shell Script

Large image assets are a massive drag on website performance. Sticking with inefficient formats like JPG or older PNGs just slows down your page loads. The best fix is switching to Google’s WebP format, which compresses images significantly without a massive drop in quality.

Converting files one by one is a waste of time, so I use cwebp, a command-line tool, to speed things up. By using the -q 80 flag, I found a good middle ground: the images stay sharp, but the file size drops drastically.

The tricky part is that cwebp can't handle every format directly. Files like .bmp or .gif have to be turned into PNGs first before they can become WebP. To avoid that tedious, repetitive process, I wrote an automation script that crawls through an entire directory and its subdirectories. The script detects the file format, handles the two-step conversion if necessary, and then deletes the original files to keep storage clean.

Here is the script I use:

bash
find . -type f \( -name "*.jpg" -o -name "*.jpeg" -o -name "*.png" -o -name "*.bmp" -o -name "*.gif" \) | while read -r file; do ext="${file##*.}" output="${file%.*}.webp" if [ "$ext" = "gif" ] || [ "$ext" = "bmp" ]; then convert "$file" "${file%.*}.png" cwebp -q 80 "${file%.*}.png" -o "$output" rm "${file%.*}.png" else cwebp -q 80 "$file" -o "$output" fi rm "$file" echo "Converted $file to $output" done

This automation has its downsides, though. Since the script deletes the original files immediately after processing, running it in the wrong folder can be a disaster. Always make sure you have a backup of your original assets before you start blasting ahead with the script.

Finding the balance between workflow efficiency and data safety is the real trick to managing digital assets. Happy coding.