Batch converting JPG and PNG to WebP

I’ve been speed optimizing some of my personal sites, and one easy update is changing the images from being JPEGs and PNG images to the smaller WebP format.

All the images I need to convert are usually in collections, where one folder at a time needs conversion and as some contain a lot of images, I needed a way to do it smartly.

This is what I came up with:

For JPEGs

find . -type f -name "*.jpg" | while read file; do cwebp -lossless "$file" -o "${file%.jpg}.webp"; done

For PNGs

find . -type f -name "*.png" | while read file; do cwebp -lossless "$file" -o "${file%.png}.webp"; done

The one-liners find all jpegs (or pngs) in the folder and converts it into a lossless webp version. It leaves the original image as a backup. For further optimizations the “cweb -lossless” could be changes to:

  • cweb - no parameters creates a compress version.
  • cwebp -q 75 - makes a smaller file as some loss of data occur during compression.
  • cwebp -lossless -z 9 - creates a lossless version using more compression.

The cwebp documentation has a more details if you want to explore how WebP images may be optimized harder.