Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Batch convert PNG files to WebP in 1 directory
# cd to the directory of the image so we can work with just filenames
dir="$(dirname "$1")"
cd "$dir" || exit 1
base="$(basename "$1" .png)"
# create a WebP version of the PNG
cwebp -q 80 "$base".png -o "$base".webp
# delete the WebP file if it is equal size or larger than the original PNG
if [[ `stat -c '%s' "$base".webp` -ge `stat -c '%s' "$base".png` ]]; then
echo "Deleting WebP file that is no smaller than PNG"
rm -f "$base".webp
# delete the WebP file if it is size 0
if [[ -f "$base".webp && ! -s "$base".webp ]]; then
echo "Deleting empty WebP file"
rm -f "$base".webp
find . -regextype posix-egrep \
-maxdepth 1 \
-type f \
-iregex '.*\.png$' \
-exec test '{}'.webp -ot '{}' \; \
-execdir "$(dirname $(readlink -f -- $0))"/convert-png-to-webp '{}' \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.