tags:

views:

152

answers:

2
+2  Q: 

Java image scaling

I am outputting images to a PDF file using iText. The images always appear larger than they are supposed to. According to the book (iText in Action), this is because iText always displays the images at a resolution of 72 dpi, regardless of what the actual dpi property of the image is. The book suggests using image.getDpiX() to find the dpi of the image, and then using image.scalePercent(72 / actualDpi * 100) to display the image properly. So far, the getDpiX() property of all my images have returned 0 (I've tried 2 gifs and 1 jpg). Is there another way to figure out the actual DPI so that my images scale properly?

com.lowagie.text.Image graphic = com.lowagie.text.Image.getInstance(imgPath);
float actualDpi = graphic.getDpiX();
if (actualDpi > 0)
  //Never gets here
  graphic.scalePercent(72f / actualDpi * 100);
A: 

According to the com.lowagie.text.Image JavaDoc, the method getDpiX gets the dots-per-inch in the X direction. Returns zero if not available.

You're going to have to assume a value when the getDpiX method returns zero. 100 dpi is as good an assumption as any.

if (actualDpi <= 0) actualDpi = 100f;
graphic.scalePercent(72f / actualDpi * 100f);
Gilbert Le Blanc
A: 

For GIF, there is no place to store a "DPI" information in the file, so "actualDpi" has no meaning in that case. For JPEG, the "DPI" information can be stored in the file, but is not mandatory, and if not set: "actualDPI" has no meaning as well. The real answer is: there is no such thing as "actual DPI", either the information is provided (ie. "in this image I want 1 pixel to be rendered with this specific physical width (or height)"), or it's not. Another element is in your sentence: "always appear larger than they are supposed to"; the "supposed to" is the DPI information stored in the image. So if this information is absent, and you feel that when you open the image it seems right on the screen, then you have to calculate the density of your screen (width in number of pixels divided by the width in inches of your screen), and use that as your "actualDPI" variable.

Damien B