Convert images using the commandline (WEBP)

The smaller an image is, the more disk space and bandwidth it can save. You can easily convert images to a more efficient form with the command line by using open source tools.

Use WEBP as an image format

[Webp] is one of the best image formats in terms of efficiency. It can replace PNG, JPEG and GIF’s. Some people generate animated WebP clips from videos which replaces GIFS.

It has two modes, lossless (PNG) and lossy (JPEG). CanIUse WebP reports 97% adoption rate in browsers. AVIF and JPEGXl are “reported” to be even more efficient, but they both don’t have wide adoption yet. Stick to webp. With WEBP you can reduce a 1MB JPEG to 200KB which is extremely usefull.

You usually need to have imagemagick, graphicsmagick and cwebp installed.

sudo apt install imagemagick graphicsmagick cwebp

Convert images using graphicsmagick

gm convert jankaluza_thunderbird.jpg -resize 800x -quality 90 jankaluza_thunderbird.webp

Convert all .png files in a folder to webp. With the quality of 80

for file in *.png; do 
  cwebp -q 80 "$file" -o "${file%.png}.webp";
done

HUGO Image Snippet with automatic resizing

FIY Hugo has builtin support for automatic image resizing and compression without you needing to touch the command line, use it.

{{ with resources.Get (.Get "src") }}
  {{ $image := .Resize "800x webp Lanczos q80" }}
  <figure>

    <img src="{{ .RelPermalink }}"   loading="lazy" {{ with $.Get "title" }} title="{{ $.Get "title" }}"  alt="{{$.Get "title" }}" {{end}}>
    {{ with $.Get "title" }}<figcaption>{{ $.Get "title" }}</figcaption> {{end}}
  </figure> 
{{ end }}

This is a very old note… just published it.

Subscribe to my Newsletter

Receive emails about Linux, Programming, Automation, Life tips & Tricks and information about projects I'm working on