Batch convert all JPEG images in a folder to WebP with ImageMagick

Posted on .

I'm in the process of converting all (or at least most) images on my website to look nicer (meaning: sharper with 2x their resolution) on modern high resolution screens. This is actually fairly easy, but unfortunately this blows up the bandwidth needed to load my site.

Enter WebP! This image format is not that new anymore, but in the last couple of years browser support became high enough to make this a sensible default for most scenarios. Unfortunately, my photo editing software of choice (Adobe Lightroom) does not natively support exporting to WebP, so here's a short line of code that you can enter in your terminal to convert all JPEG images in a folder to WebP:

mogrify -format webp -quality 80 *.jpg

This is running on ImageMagick and is structured as follows:

  • -format webp is the output format of the images (you can also change this to -format jpg for example to convert this back to JPEG).
  • -quality 80 sets the compression quality (with 0 being maximally compressed and 100 having near lossless compression). I find 80 to be a good compromise between quality and file size, but your mileage may vary.
  • *.jpg searches for all files ending in .jpg. You can of course also change this to .png/.bmp/.gif/.tif/...

In my experience, most images (depending on their complexity) get reduced to around 70% percent of their original file size, and in some instances this drops to 50% or even 40% of the original size. These are in my opinion giant savings, so I'd highly recommend trying this out for yourself.

Pro tip: WebP also supports transparencies, so if you don't need pixel perfect accuracy this format is also a great way to make more complex images quite a bit smaller.

Prerequisites

  • You need to have ImageMagick (also called Imagick or even just Magick) installed. If that's not the case, you can find the installation guide over here
  • Mogrify overwrites existing images if their filenames match, so make a backup of your precious files beforehand.