+#!/bin/bash
+#
+# webp-convert.sh
+#
+# Search through HTML and PHP files in a directory, get a list of the image
+# files used (jpg/png), and convert these to webp in the same directory as
+# the originals. Can be used with a rewrite rule on the web server to
+# serve the webp file when the original is requested.
+#
+# Andrew Lorimer, January 2021
+#
+
+docroot=$1
+if [ ! $docroot ]; then
+ docroot=.
+fi;
+
+convert_count=0
+larger_count=0
+
+echo "Converting files in $docroot"
+convert_webp () {
+ # Perform the conversion. Takes input filename, output filename.
+ if [[ "$1" == *.png ]]; then
+ # PNG conversion
+ convert "$1" -quality 75 -define webp:lossless=true "$2"
+ echo "Converted $1 to $2"
+ else
+ # JPG conversion
+ convert "$1" -quality 75 "$2"
+ echo "Converted $1 to $2"
+ fi
+ ((convert_count+=1))
+
+ # Check if webp is actually smaller than original and remove if not
+ orig_size=$(stat -c%s "$1")
+ webp_size=$(stat -c%s "$2")
+ if (( webp_size > orig_size )); then
+ rm $2
+ echo "Removed $2 as it was larger than $1 ($webp_size > $orig_size)"
+ ((larger_count+=1))
+ return 1
+ fi
+ return 0
+}
+
+while read -r srcfile; do
+ while IFS= read -r file; do
+ file_path=$(echo $file | sed "s|^.|$docroot/|")
+ webp_path=$(sed 's/\.[^.]*$/.webp/' <<< "$file_path")
+
+ # Convert if not already converted
+ if [ ! -f "$webp_path" ]; then
+ convert_webp $file_path $webp_path
+ fi
+ done < <(sed -n "s:.*<img src=\"\([^\"]*\.\(jpe\?g\|png\)\)\".*:\1:p" $srcfile)
+done <<< "$(find $docroot -type f -and \( -iname "*.php" -o -iname "*.html" \))"
+
+net=$((convert_count-larger_count))
+echo "Converted $convert_count of which $larger_count were larger than the original (net $net)"