Imagemagick - a swiss army knife for manipulating images

  about 375 words   2 min

There is a CLI tool I use often to manipulate images, its name is Imagemagick. You can install it with any package management system you have depending of your OS. Imagemagick is also used in a lot of libraries to render images for various purposes.

Here is a list of commands I use quite often when I need to edit some images.

Make thumbnails

  ~ % convert -define jpeg:size=200x200 original.jpg -thumbnail 150x150^ -gravity center -extent 150x150 thumb.jpg

Resize an image

This command resizes the original image with a width of 1200 pixels and maintaining the aspect ratio.

  ~ % convert original.jpg -resize 1200 final.jpg

Add a border to an image

  ~ % convert original.jpg -bordercolor [white|black|#rgb] -border 30x30 final.jpg

For the bordercolor names you can check on the project documentation. There is acually quite a lot of color names.

Resize all images or a particular folder

  ~ % mogrify -resize 1920x1280 -quality 85 -format png *png

You can add the > sign after the resize option lixe this , -resize 1920x1280> to indicate to imagemagick to not resize images that are smaller than 1920x1280.

If you have the completion enabled in your shell, you can see all the formats available using the tab key after the format argument.

  ~ % mogrify -format
    output file format
      bmp    eps    fpx    j2k    jpeg   jpx    pbm    pcx    png
      rad    rgba   shtml  tiff   xbm    xwd    cgm    fig    gif
      jp2    jpf    miff   pcd    pdf    ppm    ras    rle    tga
      ttf    xcf    yuv    dcx    fits   html   jpc    jpg    mpeg
      pcl    pgm    ps     rgb    sgi    tif    uil    xpm

Crop an image

  ~ % convert original.jpg -crop 200x200+500+500 +repage crop-img.jpg

You need to specify the output size (200x200) plus the start position for x & y on the original photo (+500+500). You will probably have to test a couple of times before nailing it.

The +repage setting removes the virtual canvas, blank space left of original image after cropping.

Optimizing size

You can strip a lot of your metadata from your files reducing the size of the final images this way :

  ~ % convert -strip -quality 75 original.jpg final.jpg

The higher the quality option is, the larger the image will be. But maybe for some web images you dont need a full resolution image.

tools tips Imagemagick CLI