Skip to content

Instantly share code, notes, and snippets.

@nisrulz
Forked from jonjensen/convert-png-to-webp
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nisrulz/6ec53ed672c95599aaca to your computer and use it in GitHub Desktop.
Save nisrulz/6ec53ed672c95599aaca to your computer and use it in GitHub Desktop.
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