Skip to content

Instantly share code, notes, and snippets.

@mitchellkrogza
Created August 16, 2021 12:07
Show Gist options
  • Save mitchellkrogza/d768ce119cdf8273cf40a2990e9ce563 to your computer and use it in GitHub Desktop.
Save mitchellkrogza/d768ce119cdf8273cf40a2990e9ce563 to your computer and use it in GitHub Desktop.
Generate webp images from png and jpg files recursively in any web folder (uses webp command line tool)
#!/bin/bash
# ---------------------------------------------------------------------------
# Generate WebP Images - Uses cwebp command line tool for Linux
# This will generate / re-generate all webp images for all JPG and PNG files
# Being command line based it is incredibly fast
# If you don't want to re-generate existing files set generateall=0
# If you want to re-generate everything set generateall=1
# USE this script at your own risk and Only if you know what you are doing
# Written by Mitchell Krog - [email protected]
# https://github.com/mitchellkrogza
# ---------------------------------------------------------------------------
# -------- #
# SETTINGS #
# -------- #
generateall=0 # <--- Set to 1 to re-generate all webp files / 0 will only generate missing webp files
mydomain="mydomain.com" # <--- Enter your domain / folder name here
directory="/srv/http/${mydomain}/wp-content/uploads/" # <--- Some servers use /var/www change if necessary - Change folder structure as needed
quality=80
# ------------ #
# END SETTINGS #
# ------------ #
if [[ "${generateall}" == 1 ]]
then
for file in $(find ${directory} -type f \( -name "*.jpg" -o -name "*.png" \))
do
echo "converting ${file}"
cwebp -q ${quality} -lossless ${file} -o "${file%.*}.webp"
done
else
for file in $(find ${directory} -type f \( -name "*.jpg" -o -name "*.png" \))
do
if test -f "${file%.*}.webp"
then
echo "file exists - skipping"
else
echo "convert ${file}"
cwebp -q ${quality} -lossless ${file} -o "${file%.*}.webp"
fi
done
fi
exit 0
@mitchellkrogza
Copy link
Author

Hi @andyg2 it can be done through an .htaccess rewrite or an Nginx rule. The proper way it to use a vary method of serving the images.

Ooh, I'd never head of Vary Accept, I'll be using this for sure, thanks!

This is essentially what plugins do for you but you only need this short bit of code at server level and no plugins are required to serve webp to appropriate devices.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment