Converting images to WebP recursively from command line
I recently found myself having to optimize several images, converting them from .jpeg
to .webP
. There’s an app I use for audio and video conversion via terminal: ffmpeg. I wondered if it would handle this image conversions as well, and as soon as I found it did I thought it would be a good idea to automate this task.
So, this was definitely a great candidate for a Bash script. I placed the script in the folder were the images were sitting and it took care of it in a matter of seconds. Sharing is caring:
#!/bin/bash
# Function to convert images to WebP
convert_to_webp() {
for file in "$1"/*; do
if [ -d "$file" ]; then
convert_to_webp "$file" # Recursive call for directories
elif [[ "$file" =~ \.(jpg|jpeg|png)$ ]]; then
ffmpeg -i "$file" -c:v libwebp -q:v 80 "${file%.*}.webp"
echo "Converted: $file to ${file%.*}.webp"
fi
done
}
# Start conversion from the current directory
convert_to_webp "$(pwd)"
This will convert all .jpg
, .jpeg
and .png
files in a given directory into .webP
format. Just don’t forget to make it executable with chmod +x script-name.sh
.