A while ago I optimized some images for the site you are looking at, by using the
because I had forgotten to do that, and
suggested to do so.
I forgot how to do that, so I am writing it down now. Read on if you also want to know how to convert any kind of image to webp and embed it in your site.
Install the Executable
I am using a docker setup, so I added the following line to my Dockerfile
# in Dockerfile RUN apt-get -y install webp
This installs the webp binary inside this container. The description says. It
compresses an image using the WebP format. Input format can be either PNG, JPEG, TIFF, WebP or raw Y'CbCr samples.
Note: Animated PNG and WebP files are not supported.
Convert an Image to webp
Next I want to convert images I use on my site to be available in webp too. The command I use for that runs in the docker container where I added the webp executable to. I run it via
cwebp -q 80 in.png -o out.webp
-q 80 means reduce the quality to 80%, which I am fine with.
I don't want to fiddle around too much with the quality.
in.png is the original image, in this case a png, but it can be a jpg (or see above),
I had not had any problems with other image formats yet.
-o out.webp is the file name of the resulting webp image.
For one of the images I just added I ran the following command:
cwebp -q 80 content/tidbit/2021/02/hexagonal-visual.png -o content/tidbit/2021/02/hexagonal-visual.webp
Embed in the Site
In order for (older) browsers that do not yet support webp format, a bit of HTML is needed to provide both image types.
This is done like this:
<figure> <picture> <source srcset="hexagonal-visual.webp"> <img src="hexagonal-visual.png" alt="A hexagonal diagram" width="100%" /> </picture> <figcaption>A hexagonal diagram</figcaption> </figure>
<picture> element contains multiple sources (the webp and the png image),
so the browser can choose the most appropriate one.
In short, a browser that does NOT support webp will use the other image.