开发者

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 = g开发者_如何学运维raphic.getDpiX();
if (actualDpi > 0)
  //Never gets here
  graphic.scalePercent(72f / actualDpi * 100);


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);


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.


The screen-resolution, retrieved by

java.awt.Toolkit.getDefaultToolkit().getScreenResolution()

did not help, image was still too big. However, one can scale the image to the page width in the following way:

BufferedImage bufferedImage = null; // your image
Image image = Image.getInstance(bufferedImage,null);
image.scalePercent((document.right()-document.left())/((float)image.getWidth())*100);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜