我试图将图像作为pdf文件的新页面,jpeg图像的大小太大,虽然它被添加得很好,但是在将pdf转换为Tiff时面临问题,它抛出了内存异常,是否有办法压缩这些jpeg文件
以下代码将图片转换为pdf
PDImageXObject image = PDImageXObject.createFromFile(imagePath, doc);
PDPage page = new PDPage(new PDRectangle(image.getWidth(), image.getHeight()));
doc.addPage(page);
try (PDPageContentStream contents = new PDPageContentStream(doc, page)) {
contents.drawImage(image, 0,0);
contents.close();
}
下面转换为pdf到tiff
document = PDDocument.load(new File(pdfFilename));
PDFRenderer pdfRenderer = new PDFRenderer(document);
BufferedImage[] images = new BufferedImage[document.getNumberOfPages()];
for (int i = 0; i < images.length; i++) {
PDPage page = (PDPage) document.getPage(i);
BufferedImage image;
try {
image = pdfRenderer.renderImageWithDPI(i, 300, ImageType.RGB); // its throwing outofmemory error at this line
images[i] = image;
} catch (IOException e) {
LOGGER.error("Exception while reading merged pdf file:" + e.getMessage());
throw e;
}
}
File tempFile = new File(tiffFileName+".tiff");
ImageWriter writer = ImageIO.getImageWritersByFormatName("TIFF").next();
ImageOutputStream output = ImageIO.createImageOutputStream(tempFile);
writer.setOutput(output);
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writer.prepareWriteSequence(null);
for (int i = 0; i < images.length; i++) {
params.setCompressionType("JPEG");
writer.writeToSequence(new IIOImage(images[i], null, null), params);
}
writer.endWriteSequence();
答案 0 :(得分:0)
要避免内存不足异常,请尝试使用合适的值传递Xms和Xmx参数来启动应用程序。请参阅此帖子What are the Xms and Xmx parameters when starting JVMs?和https://docs.oracle.com/cd/E21764_01/web.1111/e13814/jvm_tuning.htm#PERFM150:
设置初始和最小堆大小
-Xms Oracle建议将最小堆大小(-Xms)设置为等于最大堆大小(-Xmx),以最大限度地减少垃圾回收。
设置最大堆大小
-Xmx设置较低的最大堆值与实时数据量相比,通过强制频繁的垃圾收集来降低性能。