be7d1f73b9ae29bdb7f20f1bb9fdf184f8665497
   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.
  24  if [[ "$1" == *.png ]]; then
  25    # PNG conversion
  26    convert "$1" -quality 75 -define webp:lossless=true "$2"
  27    echo "Converted $1 to $2"
  28  else
  29    # JPG conversion
  30    convert "$1" -quality 75 "$2"
  31    echo "Converted $1 to $2"
  32  fi
  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")
  38  if (( webp_size > orig_size )); then
  39    rm $2
  40    echo "Removed $2 as it was larger than $1 ($webp_size > $orig_size)"
  41    ((larger_count+=1))
  42    return 1
  43  fi
  44  return 0
  45}
  46
  47while read -r srcfile; do
  48    while IFS= read -r file; do
  49      file_path=$(echo $file | sed "s|^.|$docroot/|")
  50      webp_path=$(sed 's/\.[^.]*$/.webp/' <<< "$file_path")
  51      
  52      # Convert if not already converted
  53      if [ ! -f "$webp_path" ]; then
  54        convert_webp $file_path $webp_path
  55      fi
  56    done < <(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_count of which $larger_count were larger than the original (net $net)"