缩放图像模糊PDFBox

时间:2014-04-22 15:23:48

标签: java image-processing pdfbox

我正在尝试将尺寸= 2496 x 3512的图像缩放为PDF文档。我正在使用PDFBox生成它,但缩放后的图像最终模糊不清。

以下是一些片段:

  • PDF页面大小(A4)由page.findMediaBox()返回.createDimension():java.awt.Dimension [width = 612,height = 792]

  • 然后我根据页面大小与图像大小计算缩放维度,该大小返回:java.awt.Dimension [width = 562,height = 792] 我使用下面的代码来计算缩放尺寸:

    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);
    }
    
  • 实际执行图像缩放我正在使用Image Scalr API:

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

我的问题是我做错了什么?缩放到较小尺寸时,不应模糊大图像。这是与PDF页面分辨率/大小相关的内容吗?

谢谢,

木桥

1 个答案:

答案 0 :(得分:13)

好的,我找到了一种在不损失质量的情况下添加图像的方法。

实际上为了使图像不被模糊,我让PDFBox通过给出所需的尺寸来调整图像的大小。像下面的代码:

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

谢谢,

木桥