gpt4 book ai didi

java - 使用 PDFbox 将 pdf 转换为 tiff 时,Tiff 图像文件为空白

转载 作者:太空宇宙 更新时间:2023-11-04 13:04:01 26 4
gpt4 key购买 nike

当我运行如下所示的代码并使用 ImageIO.getImageWritersBySuffix("tiff") 而不是 jpg 时,会创建 tiff 文件,但它们是空白的且为 0 字节。

import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

public class Converter {

/**
* @param args
*/
public static void main(String[] args) {
PDDocument pdf;
BufferedWriter wr;
try {
File input = new File("C:\\test.pdf");
pdf = PDDocument.load(input);
List<PDPage> pages = pdf.getDocumentCatalog().getAllPages();

for (int i = 0; i < pdf.getNumberOfPages(); i++) {
ImageOutputStream imgOutStream = null;
ImageWriter imageWriter = null;

try {
PDPage page = (PDPage) pages.get(i);
BufferedImage image = page.convertToImage();
String fileName = "C:\\TIFF" + (i + 1) + ".tif";
imgOutStream = ImageIO.createImageOutputStream(new File(fileName));

boolean foundWriter = false;
// Iterator<ImageWriter> writerIter =
ImageIO.getImageWritersByFormatName("jpg");
Iterator<ImageWriter> writerIter = ImageIO.getImageWritersBySuffix("tiff");

while (writerIter.hasNext() && writerIter != null) {
try {
imageWriter = (ImageWriter) writerIter.next();

ImageWriteParam writerParams = imageWriter.getDefaultWriteParam();
if (writerParams.canWriteCompressed()) {
writerParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writerParams.setCompressionQuality(1.0f);
}

imageWriter.setOutput(imgOutStream);
imageWriter.write(null, new IIOImage(image, null, null), writerParams);
foundWriter = true;
} catch (Exception ex) {
System.out.println("1. exception occured...");
ex.printStackTrace();
} finally {
if (imageWriter != null) {
imageWriter.dispose();
}
}

if (!foundWriter) {
System.out.println("Image writer not found");
}

}

} catch (Exception ex) {
System.out.println("2. exception occured...");
ex.printStackTrace();
}

}

if (pdf != null) {
pdf.close();
}

// close to flush the stream.
// wr.close();

} catch (Exception e) {
e.printStackTrace();
}
}

}

最佳答案

为什么要费心去处理复杂的代码和棘手的问题呢?改用这个:

ImageIOUtil.writeImage(image, fileName, 72);

这将创建一个 72 dpi 的 TIFF 文件(这是调用 ConvertToImage() 时获得的分辨率)。文件名必须以“.tif”或“.tiff”结尾。

重要提示:您需要使用 jai_imageio.jar 库。

关于java - 使用 PDFbox 将 pdf 转换为 tiff 时,Tiff 图像文件为空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34664021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com