Converting images to WebP

Let's say i was looking for a way to convert images into a format, that is perfectly suited for modern webhosting. That means, good compatibility, decent enough quality and (most important) low file size.

The classics are .jpg and .png, which are also the best supported, and are good enough for most usecases. But...there is also another one, that is getting better support with each year, while providing smaller file sizes compared to the above mentioned formats. And that is WebP. Yes, there is also AVIF, but at the time of writing this article, its support if not as great (yet).

Now, there comes just one little problem...converting whatever you have into .webp seamlessly is a pain. So, i have been looking for solutions, and i will share some of them here with you.

Using ImageMagick

Probably easiest to use and most flexible, but requires the ImageMagick software. Can also pre and post process images and supports lots of different image formats. Truly the swiss army knife for image processing over the CLI.

Here is a simple Linux script (using the installed imagemagick package on Linux Mint) that converts whatever image file into a separate .webp image file.

#!/usr/bin/env bash
image_filepath="${1}"

convert "${image_filepath}" -quality 100 "${image_filepath%.*}.webp"

Keep you eye out to the -quality parameter. This one determines if you want lossless (=100) or lossy (<100) compression.

Using ffmpeg

If going overkill or it being the only tool available by choice or circumstances, then yes, you can convert different image formats to .webp with it.

Simplest terminal/command-line command i know of is ffmpeg -i <input filepath> -codec libwebp <output filename>.webp, which will get the job done in most cases. For extra control, there are several options available, but for most usecases, -lossless and -quality are good enough.

The argument -lossless is used to set if lossless (set to 1) or lossy (set to 0) compression is to be used in the encoding process, while -quality determines the image quality (from 0 to 100).

Here is a Bash script using lossless compression.

#!/usr/bin/env bash
image_filepath="${1}"

ffmpeg -i "${image_filepath}" -codec libwebp -lossless 1 "${image_filepath%.*}.webp"

And also one using lossy compression.

#!/usr/bin/env bash
image_filepath="${1}"

ffmpeg -i "${image_filepath}" -codec libwebp -lossless 0 -quality 75 "${image_filepath%.*}.webp"

There are several different ways to do the same thing, so just use the ones that save you time and energy.

Which settings to use

If your image is complex (lets say, landscape with lots of objects), i recommend using lossy compression and playing with the -quality parameter abit. Serves as a alternative to .jpg.

For logos or simpler images, that cannot hide compression artifacts in complex geometry, i recommend using lossless compression, which can serve as a alternative to .png.

Links

Social