1

Bulk Convert to Modern Image Format with Image Magik Script

Apparently the days of good ol PNG are over. Or at least that's what the site optimization scanners are telling me. To blindly adhere and increase my SEO I'm just going to straight convert all my images to a modern format. I chose WebP Because it's apparently the easiest blind choice for web these days.

Setup

Install ImageMagik from here, make sure it is added to your PATH variable in whatever shell you're using. We're going to need convert. If you're on UNIX or MacOS you'll also need to install the webp from libwebp.

Script

I wanted a script that would recursively go through every subdirectory and convert any found images to WebP. Here's what I came up with:

  • find -follow creates a nice iteration of all the files below pwd. Note: This deletes the old files, do ensure you have a backup before you try this, or just remove the deletion line rm $f.
#!/bin/bash
for f in `find $1 -follow`; do 
    dir=$(dirname $f)
    filename=$(basename -- "$f")
    ext="${filename##*.}"
    filename="${filename%.*}"
    if [ "$ext" == "png" -o "$ext" == "PNG" -o "$ext" == "jpg" -o "$ext" == "JPG" ]; then
        echo "Converting $f"
        convert "$f" "$dir/$filename.webp"
        echo "Done $filename.webp"
        rm $f
    else
        if [ ! -d "$f" ]; then
            printf "Error:\n Unsupported format: $f\n"
        fi
    fi
done

I added this to the root of my web repo so I can eventually stuff it into a CI job. I really don't want to have to think about converting screenshots to this format all the time!