The WebP format is recommended among best practices for optimizing website performance due to its ability to significantly reduce the size of images saved in other formats. In this article, we will see how to create a Bash script to convert existing images to the WebP format.
Before implementing our script, it is necessary to install the webp
package on the machine where we want to perform the conversion operation. This package is available for all the most popular and widely used package managers.
Once this is done, we will have access to the cwebp
command, which will perform the conversion with the following syntax:
cwebp image.jpg -o image.webp
Our script should ensure that if the converted image already exists, it is not converted again, and the original image is removed.
#!/bin/bash
# Base directory passed as an argument
START_DIR=$1
# Check if the directory exists
if [ ! -d "$START_DIR" ]; then
exit 1
fi
# Find all PNG and JPEG/JPG images and convert them to WebP
find "$START_DIR" -type f \( -iname "*.png" -o -iname "*.jpg" -o -iname "*.jpeg" \) | while read IMAGE; do
# Create the WebP file name
WEBP_IMAGE="${IMAGE%.*}.webp"
# Check if the WebP file already exists to avoid duplicate conversions
if [ ! -f "$WEBP_IMAGE" ]; then
echo "$IMAGE -> $WEBP_IMAGE"
cwebp "$IMAGE" -o "$WEBP_IMAGE" &> /dev/null
if [ -f "$WEBP_IMAGE" ]; then
# Remove the original file
rm "$IMAGE"
echo "Removed $IMAGE"
fi
else
echo "The file $WEBP_IMAGE already exists, skipping conversion."
fi
done
echo "Conversion completed!"
After making the Bash script executable, we can use it as follows:
./convert-webp.sh public_html/uploads
Conclusion
Converting website images to the WebP format is a great way to significantly reduce their size, thereby improving performance and user experience.