Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java image scaling

Tags:

java

image

itext

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);
like image 497
twpc Avatar asked May 25 '10 14:05

twpc


People also ask

Can you resize an image in Java?

You can resize an image in Java using the getScaledInstance() function, available in the Java Image class. We'll use the BufferedImage class that extends the basic Image class.

How do I resize an image to scale?

Step 1: Right-click on the image and select Open. If Preview is not your default image viewer, select Open With followed by Preview instead. Step 2: Select Tools on the menu bar. Step 3: Select Adjust Size on the drop-down menu.


1 Answers

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);
like image 127
Gilbert Le Blanc Avatar answered Nov 08 '22 06:11

Gilbert Le Blanc