Obtain image file information using the Linux shell

Sometimes you have to evaluate an image, ie. find out what its width and height is and check against a maximum or minimum and based on the outcome take certain actions. You want to do this using the Linux shell.


1 answer

Getting image width and height in Linux

imagemagick is a linux command line tool with many options to manipulate image files.
It allows you to resize an image, change between image formats and also work with pdfs (converting pdfs to images and vice versa, split and merge pdfs etc.)

One of the tools that come with imagemagick is called identify, which produces an output like

Image: rose.jpg
Format: JPEG (Joint Photographic Experts Group JFIF format)
Class: DirectClass
Geometry: 70x46+0+0
Resolution: 72x72
Print size: 0.972222x0.638889
Units: PixelsPerInch
Type: TrueColor
Endianess: Undefined
Colorspace: RGB
Depth: 8-bit
Channel depth:
red: 8-bit
green: 8-bit
blue: 8-bit
Channel statistics:
min: 37 (0.145098)
max: 255 (1)
mean: 145.58 (0.5709)
standard deviation: 67.3195 (0.263998)

The "Geometry" line: Geometry: 70x46+0+0 contains the width x height, in this case 70x46 pixels, if you want to get the width "70" and height "46" without messing around with regexp you can use awk to do this in the following way

res=`identify -verbose $f | grep Geometry | awk '{print $2}' | awk -F+ '{print $1}'`
width=`echo $res | awk -Fx '{print $1}'`
height=`echo $res | awk -Fx '{print $2}'`

you first get the geometry line from the identify output using grep, then split it along white spaces getting "70x46+0+0", further you split that up along the + getting "70x46"

you then extract the width doing the exact same thing but splitting along the x and then getting the first element (the width) and the second (the height)