While working on a project I needed a quick and customizable way of converting a lot of JPEG images to the much better webp format. Additionally, the tool also needed to resize the image if it is above a certain size (while still maintaining the aspect ratio if not 1:1), compress the image to a given quality and finally set a background color if the source is transparent. At first, I started to look for an existing tool – in the end I just came up with a quick shell script. Exercise is important!
#!/bin/bash
# Usage: x2webp.sh png 1000x1000 75 transparent
if [ -z "$1" ]; then
echo "Please provide the file type flag (e.g. avif, jpg, jpeg, png, etc.)"
exit 1
fi
if [ -z "$2" ]; then
echo "Please provide the dimensions to rescale to (e.g. 1000 - only the width will be changed, the aspect ratio will be preserved)"
exit 1
fi
if [ -z "$3" ]; then
echo "Please provide the quality of the compression (e.g. 65 - retains 65% quality of the original)"
exit 1
fi
if [ -z "$4" ]; then
echo "Please provide a background color or just pass 'transparent' as the value"
exit 1
fi
TYPE="$1"
SIZE="$2"
QUALITY="$3"
BG="$4"
# Convert all images with the specified image type to webp using ImageMagick
for file in *."$TYPE"; do
# magick "$file" "${file%.*}.png"
convert "$file" -background "$BG" -flatten "${file%.*}.webp";
done
# Downscale images or do nothing if original dimensions are larger than specified (again using ImageMagick)
for file in *.webp; do
if [ $(identify -format '%w' "$file") -gt "${SIZE%x*}" ] || [ $(identify -format '%h' "$file") -gt "${SIZE#*x}" ]; then
convert "$file" -resize "$SIZE"\> "$file"
fi
done
# Compress images while still retaining acceptable quality (65%~) using cwebp
for file in *.webp; do
cwebp -q "$QUALITY" "$file" -o "${file%.*}_compressed.webp"
done
As always, do be able to run this shell script in the console, you need to grant the current user execution permissions like below (assuming you named the script “x2webp.sh”)…
chmod u+x x2webp.sh