← All recipes

Bulk Convert Images to WebP

Create ~/private/bulk-convert-to-webp.sh with the following. Then chmod +x ~/private/bulk-convert-to-webp.sh to grant execute permissions and ~/private/bulk-convert-to-webp.sh to run. Targets images larger then 1MB.

#!/bin/bash

if ! which cwebp &> /dev/null
then
    cd ~/private
    if [ -f "libwebp-1.5.0-linux-x86-64/bin/cwebp" ]
    then
        cwebp() {
          ~/private/libwebp-1.5.0-linux-x86-64/bin/cwebp "$@"
        }
    fi
    if ! cwebp --version &> /dev/null
    then
       wget --quiet https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-1.5.0-linux-x86-64.tar.gz
       tar -xvzf libwebp-1.5.0-linux-x86-64.tar.gz
       cwebp() {
          ~/private/libwebp-1.5.0-linux-x86-64/bin/cwebp "$@"
       }
   fi
fi

cd ~/public

before_size="$( du -sh wp-content/uploads/| awk '{print $1}' )"
echo "Current uploads size: $before_size"
files=$(find wp-content/uploads/ -type f -size +1M \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \))
count=$(echo "$files" | wc -l)

if [[ $files == "" ]]; then
   echo "No images found."
   return
fi
echo "Total number of photos over 1MB: $count"

echo "$files" | while IFS= read -r file; do
    format=$( identify -format "%m" "$file" )
    if [ "$format" == "WEBP" ]; then
        continue;
    fi
    before_size=$( du -sh --apparent-size "$file" | awk '{print $1}' )
    cwebp -q 80 "$file" -o "$file.temp.webp" > /dev/null 2>&1
    # Check if the conversion succeeded and the temporary file is non-zero in size
    if [ -s "$file.temp.webp" ]; then
        # Move the temp file to the original file, overwriting it
        mv "$file.temp.webp" "$file"
    else
        # If conversion failed, remove the empty temp file
        rm -f "$file.temp.webp"
        echo "Conversion failed for $file"
        continue
    fi
    after_size=$( du -sh --apparent-size "$file" | awk '{print $1}' )
    echo "Converting from $format to WEBP ($before_size -> $after_size): $file"
done

after_size="$( du -sh wp-content/uploads/ | awk '{print $1}' )"
echo "Uploads reduced from $before_size to $after_size through bulk WEBP conversion"
Run it across a fleet

Open the console in CaptainCore Manager, pick the target sites, choose this recipe from the Cookbook picker and press run. The CLI streams each site's output back to the dock.

About the console →