Scaled image blurry in PDFBox

I am trying to scale an image of size = 2496 x 3512 to a PDF document. I use the PDFBox to create it, but the scaled image ends up blurry.

Here are some snippets:

  • PDF The page size (A4) returned by page.findMediaBox (). createDimension (): java.awt.Dimension [width = 612, height = 792]

  • Then I calculate the scale dimension based on the page size and image size that returns: java.awt.Dimension [width = 562, height = 792] I use the following code to calculate the scaled size:

    public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) { int original_width = imgSize.width; int original_height = imgSize.height; int bound_width = boundary.width; int bound_height = boundary.height; int new_width = original_width; int new_height = original_height; // first check if we need to scale width if (original_width > bound_width) { //scale width to fit new_width = bound_width; //scale height to maintain aspect ratio new_height = (new_width * original_height) / original_width; } // then check if we need to scale even with the new height if (new_height > bound_height) { //scale height to fit instead new_height = bound_height; //scale width to maintain aspect ratio new_width = (new_height * original_width) / original_height; } return new Dimension(new_width, new_height); } 
  • And to actually scale the image, I use the Image Scalr API:

     BufferedImage newImg = Scalr.resize(img, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT, scaledWidth, scaledHeight, Scalr.OP_ANTIALIAS); 

My question is what am I doing wrong? A large image should not be blurry when zoomed to a smaller size. Is this related to pdf resolution / page size?

Thanks,

Ge

+7
java image-processing pdfbox
source share
1 answer

Well, I found a way to add images without losing quality.

Actually, so that the image is not blurry, I let the PDFBox resize the image, giving it the desired size. Like the code below:

 PDXObjectImage ximage = new PDJpeg(doc, new FileInputStream(new File("/usr/gyo/my_large_image.jpg")), 1.0f); PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false); Dimension scaledDim = getScaledDimension(new Dimension(ximage.getWidth(), ximage.getHeight()), page.getMediaBox().createDimension()); contentStream.drawXObject(ximage, 1, 1, scaledDim.width, scaledDim.height); contentStream.close(); 

Thanks,

Ge

+12
source share

All Articles