1#!/bin/bash 2# 3# webp-convert.sh 4# 5# Search through HTML and PHP files in a directory, get a list of the image 6# files used (jpg/png), and convert these to webp in the same directory as 7# the originals. Can be used with a rewrite rule on the web server to 8# serve the webp file when the original is requested. 9# 10# Andrew Lorimer, January 2021 11# 12 13docroot=$1 14if[ !$docroot];then 15 docroot=. 16fi; 17 18convert_count=0 19larger_count=0 20 21echo"Converting files in$docroot" 22convert_webp () { 23# Perform the conversion. Takes input filename, output filename. 24if[["$1"== *.png ]];then 25# PNG conversion 26 convert "$1"-quality75-define webp:lossless=true "$2" 27echo"Converted$1to$2" 28else 29# JPG conversion 30 convert "$1"-quality75"$2" 31echo"Converted$1to$2" 32fi 33((convert_count+=1)) 34 35# Check if webp is actually smaller than original and remove if not 36 orig_size=$(stat -c%s "$1") 37 webp_size=$(stat -c%s "$2") 38if(( webp_size > orig_size ));then 39rm$2 40echo"Removed$2as it was larger than$1($webp_size>$orig_size)" 41((larger_count+=1)) 42return1 43fi 44return0 45} 46 47whileread -r srcfile;do 48while IFS=read -rfile;do 49 file_path=$(echo $file | sed "s|^.|$docroot/|") 50 webp_path=$(sed 's/\.[^.]*$/.webp/' <<< "$file_path") 51 52# Convert if not already converted 53if[ !-f"$webp_path"];then 54 convert_webp $file_path $webp_path 55fi 56done< <(sed-n"s:.*<img src=\"\([^\"]*\.\(jpe\?g\|png\)\)\".*:\1:p"$srcfile) 57done<<<"$(find $docroot -type f -and \( -iname "*.php" -o -iname "*.html" \))" 58 59net=$((convert_count-larger_count)) 60echo"Converted$convert_countof which$larger_countwere larger than the original (net$net)"