Terminal Image Manipulation

Recipes for manipulating images from the command line

by Hadley Bradley

As a web developer there are many instances in which you need to interact with images. Maybe you need to rotate or resize an image before posting it to your web site. In most cases, you’ll not need a fully blown image editor like Gimp installed on your machine. With ImageMagick and other command line tools, such as jpegtran, you can accomplish a lot from the terminal. Here is a list of the commands I use on a regular basis.

 Get dimensions of an image

identify input.jpg

Which will return the dimensions like:

input.jpg JPEG 3264x2448 3264x2448+0+0 8-bit sRGB

 Rotate an image

You can rotate an image through 90 or 180 degrees by using the jpegtran command:

jpegtran -rotate 90 input.jpg > output.jpg

 Resize an image maintaining aspect ratio

You can use the convert command from the ImageMagic library to resize an image to a specific width while maintaining the aspect ration for the images height. In this example, we resize the input image to a maximum width of 700 pixels. We also reduce the quality of the JPG compression to 80%.

convert -geometry 700x input.jpg -quality 80 output.jpg

You can also resize the image by fixing the height and maintaining the aspect ration. In this example we’re resizing the image to a fixed height of 400 pixels. Th

convert -geometry x400 input.jpg -quality 80 output.jpg

 Prepare an image for a website

To prepare a JPG image which is as small as possible for website performance we should remove all the EXIF data and remove the embedded thumbnail that many cameras generate. The command below does this, while also converting the JPG to use a progressive encoding. The progressive encoding can make the image appear to load faster over slow internet connections, as it renders the image in stages to make it appear it’s being streamed in.

jpegtran -copy none -progressive -optimize input.jpg > output.jpg

 Remove colour from an image

To convert a JPG image to a greyscale black and white photo use the following command:

jpegtran -greyscale input.jpg > grey.jpg

Table of Contents

  1. Get dimensions of an image
  2. Rotate an image
  3. Resize an image maintaining aspect ratio
  4. Prepare an image for a website
  5. Remove colour from an image