Introduction
This tutorial will guide you through the process of recursively converting images to WebP format. You'll learn how to convert images in bulk, using a command-line tool for automating the process.
This can be particularly useful when dealing with large batches of images, or when making sure all your website's assets are optimized.
What is the WebP format?
WebP is a modern image format that provides superior lossless and lossy compression for images on the web.
It's currently supported by all major browsers, meaning you can serve WebP images to your visitors without any issues, WebP browser compatibility. WebP images are typically much smaller in size than other web formats, such as JPEG and PNG, resulting in faster loading times.
How much can you save by using WebP?
When it comes to file sizes, WebP images are usually much smaller than the same image in other web formats.
According to many sources, you can typically save around 25-35% of your image size when automatically converting from a PNG or JPEG format to WebP.
Install cwebp
Cwebp is a powerful command-line tool that can convert images to WebP format.
Linux: sudo apt-get install webp
Mac: brew install webp
Bulk convert all images to .webp bash script
This bash script will recursively convert all *.jpg|*.jpeg|*.png|*.gif
images to WebP format.
Script usage: ./convert-images-to-webp.sh -dir /path/to/dir
chmod +x ./convert-images-to-webp.sh
#!/bin/bash
convert_to_webp () {
local savings=0
for file in "$1"/*; do
if [ -d "$file" ]; then
convert_to_webp "$file"
elif [ -f "$file" ]; then
case "$file" in
*.jpg|*.jpeg|*.png|*.gif)
output_file="${file%.*}.webp"
cwebp -q 80 "$file" -o "$output_file"
original_size=$(wc -c <"$file")
new_size=$(wc -c <"$output_file")
if [ $new_size -lt $original_size ]; then
savings=$(( savings + (original_size - new_size) / 1024 ))
fi
;;
esac
fi
done
echo "$savings"
}
if [ "$1" == "-dir" ]; then
if [ -d "$2" ]; then
savings=$(convert_to_webp "$2")
echo "Total savings: $(bc <<< "scale=2; $savings / 1024") MB"
else
echo "Error: $2 is not a directory."
fi
else
echo "Usage: $0 -dir [directory]"
fi
Once the script is finished, it'll show you how much data you've saved!
Your original files will not be deleted, if you'd like to delete the originals to conserve space and only keep webp versions, you can run the following command:
find /path/to/dir -type f ( -name ".jpg" -o -name ".jpeg" -o -name ".png" -o -name ".gif" ) -delete
Useful Resources
Summary
In this tutorial, you have learned how to convert images in bulk to .webp format using a command-line tool. You also learned about the advantages of WebP and why it is recommended for web developers.
Finally, you saw an example bash script that can be used for recursively converting images to WebP format. Now you can optimize your website's assets with ease!