Lukap
Lukap

Reputation: 31963

Parse image size from identify command

with identify command I get some info about images and it looks like this

my_image.png PNG 154x78 154x78+0+0 8-bit DirectClass 946B 0.000u 0:00.000

the image size it is 154x78

but I do not know how to put this values in variables

w=154 #But I want this 154 to be somehow parsed...
h=78

Note this script for parsing should work for all kind of images not just for the .png extension

also if possible I want to know what is the 0+0 in this line 154x78+0+0

Thanks

Upvotes: 1

Views: 626

Answers (2)

beerbajay
beerbajay

Reputation: 20270

This is a difficult case to write a regex for, since we don't know if the file name will contain spaces or have an extension or not. Easier would be to use the format switch for identify:

identify -format '%w' filename.jpg
3360
identify -format '%h' filename.jpg
1080

In bash, you'd write:

W=`identify -format '%w' filename.jpg`
H=`identify -format '%h' filename.jpg`

The +0+0 is the offset for the image, +0+0 just means start at 0 on the x axis, and 0 on the y axis. You can read more in the imagemagick manual.

Edited by Mark Setchell

The foregoing answer is perfectly good, and I didn't want to add a competing answer, just a clarification, or minor improvement, that is too big for a comment...

As the OP is using bash, he can get both the width and height in one go, without opening the image multiple times, like this:

read w h < <(identify -format "%w %h" filename.jpg)

along with anything else, such as the colorspace and number of unique colours:

read w h c u < <(identify -format "%w %h %[colorspace] %k" filename.jpg)

Upvotes: 7

Kristofer
Kristofer

Reputation: 3269

Using awk with multiple delimiters (space and x) should work

You could try with w = $(.....) if backticks don't work.

w = `awk -F" |x" '{print $3}'`
h = `awk -F" |x" '{print $4}'`

You need to fit in the identify command's output to the above, either by pre storing it in a file and passing that in, or including the call .

Upvotes: 0

Related Questions