Created
August 16, 2021 12:07
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.