Skip to content

Instantly share code, notes, and snippets.

@mattkenefick
Created February 9, 2023 14:53
Show Gist options
  • Save mattkenefick/c7599f20bbc4cca8132d8ce989411efc to your computer and use it in GitHub Desktop.
Save mattkenefick/c7599f20bbc4cca8132d8ce989411efc to your computer and use it in GitHub Desktop.
Convert a file or directory into webp files from jpg, jpeg, or png
#
# Convert a file, or folder, into webp
# Example:
# toWebp splash-01.png
# toWebp splash-01.jpg
# toWebp splash-01.jpeg
# toWebp ./images
# toWebp
#
toWebp() {
input=${1:-.}
# Check if input is a directory
if [ -d "$input" ]; then
for file in "$input"/*.{png,jpg,jpeg}; do
filename="${file##*/}"
# Make sure filename is not "*.jpeg" or "*.png"
# Usually indicates no files found
if [ "$filename" == "*.jpeg" ] || [ "$filename" == "*.png" ] || [ "$filename" == "*.jpg" ]; then
continue
fi
# Check if converted webp already exists
if [ -f "${filename%.*}.webp" ]; then
echo "Skipping ${filename%.*}.webp"
continue
fi
ffmpeg -i "$file" -c:v libwebp -q:v 90 "${file%.*}.webp"
done
# Input must be a file
else
filename="${input##*/}"
ffmpeg -i "$input" -c:v libwebp -q:v 90 "${input%.*}.webp"
fi
}

Install this script into your ~/.bashrc or ~/.bash_profile file.

Open a new shell or source the file you used, e.g. source ~/.bashrc

Navigate to the folder you want to convert

$ toWebp my-image.png

or

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