Ultimately, I'm trying to determine the size of an image in inches so I can be certain it lays out properly on the printer.
If I use the command identify document.pdf
I get the following output:
document.pdf PDF 612x792 612x792+0+0 16-bit sRGB 29289B 0.000u 0:00.000
If I divide 612 and 792 each by 72 respectively, I get 8.5×11 which tells me the size. I know this is correct because I printed it. The problem is, it's not always going to be 8.5×11 nor will the DPI always be the same (and I won't be there to "know" how it was printed/saved).
From ImageMagic's page on using Identify they have a -verbose
output flag and an example of "calculating an image size at 72 DPI" but they don't say how they got the DPI!
How can I programmatically determine the DPI of an image?
(Graphics are bit out of my wheelhouse and with the sheer volume of ImageMagick's options along with terms I'm not familiar with is a bit like drinking from the fire hose.)
Best Answer
(Thanks to Tetsujin for his helpful comments leading me to the answer)
ImageMagick can get a little confusing with their myriad of options when you're attempting to do something. There's a couple of ways that you can find out the DPI of an image. Both of them use the
identify
command.For the examples below, I'm using a sample, royalty free photo of an Apple iMac saved natively as a JPG and exported as a PNG.
Manually calculating the size. To do this, we need two pieces of information, the resolution and the Units. In this case, we lucked out because the the units are in PPI (pixels per inch) so the resolution makes sense - it's 72 PPI or 72 DPI
However, if the image file is a PNG, things are stored as PPCM or pixels per centimeter. Issuing the same command:
This tells us that it's 28.34 PPCM. To get DPI we have to do a little calculation. 1in = 2.54cm, so to get DPI we multiply that to the resolution as follows:
Real-time Calculation. Again, using JPEG, we know that it's resolution is in DPI, so we just need to get the resolution value using the
-format flag
and the the percent (%) escape sequences:Since PNG files are in PPCM, we can use the calculated FX expressions and the percent (%) escape sequences, to calculate this value. Here, we're getting the resolution value and multiplying it by 2.54 to get DPI.
Note: You can get the units using the %[units] escape sequence here:
Calculate the size. We can now calculate the size (inches) of the image. Here, we use the
%[w]
escape sequence to get the width in DPI or PPCMDivide by 72 to get inches