Use imagemagick to convert and compress images

imagemagick: https://imagemagick.org/ is a free and open source image editing tool. I use it to compress images before uploading to my server to save some disk space.

Installation

Installation instruction is provided on the official website: install imagemagick .

For mac users, homebrew will take care of it:

1
brew install imagemagick

The recommended way in Linux is to use the portable AppImage distribution. It is also strongly encouraged to set up security policy for it. Refer to the official link above for more details and other distributions.

1
wget https://imagemagick.org/archive/binaries/magick

Visit install imagemagick and scroll down to the end to download window binaries.

Usage

I mainly use it to compress images. I convert the images to WebP and reduce the quality to 50 or 60 which usually halves the size while keeping enough pixels.

The CLI for mac and linux is a bit different. In Mac OS, everything is under magick command, while in Linux, commands are split into several binaries.

Convert and compress one image

1
magick INPUT.jpg -format webP -quality 60 OUTPUT.webP

replace magick with convert. (Not tested.)

Batch processing

I put the following script in my blog image folder and run it before I upload my content. It will convert and compress all .jpg images to webP and then remove original copy. Adjust .jpg to any other image format as needed.

1
2
3
4
5
6
7
8
9
#!/usr/bin/env bash

echo Before compress:
du -d 1 -h
echo compressing...
find . -name '*.jpg' | xargs magick mogrify -format webP -quality 60
find . -name '*.jpg' | xargs rm
echo After compress:
du -d 1 -h

replace magick mogrify with mogrify. (Not tested.)