Create a gist now

Instantly share code, notes, and snippets.

Batch convert PNG files to WebP in 1 directory
#!/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
# 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
fi
# 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
fi
#!/bin/bash
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