pdf 轉png (多頁pdf轉一張png) aspose pdf jar


/**
* 將pdf轉圖片
*/
public static void pdfToImage(InputStream inputStream, File imgFile) {
try {
long old = System.currentTimeMillis();
System.out.println("begin..............");
Document pdfDocument = new Document(inputStream);
Resolution resolution = new Resolution(130);
JpegDevice jpegDevice = new JpegDevice(resolution);
List<BufferedImage> imageList = new ArrayList<BufferedImage>();
List<File> fileList = new ArrayList<>();
for (int index = 1; index <= pdfDocument.getPages().size(); index++) {
File file = File.createTempFile("tempFile", "png");
FileOutputStream fileOS = new FileOutputStream(file);
jpegDevice.process(pdfDocument.getPages().get_Item(index), fileOS);
fileOS.close();
imageList.add(ImageIO.read(file));
fileList.add(file);
}
//臨時文件刪除
BufferedImage mergeImage = mergeImage(false, imageList);
ImageIO.write(mergeImage, "png", imgFile);
long now = System.currentTimeMillis();
System.out.println("共耗時:" + ((now - old) / 1000.0) + "秒");
//刪除臨時文件
for (File f : fileList) {
f.delete();
}
} catch (Exception e) {
e.printStackTrace();
}

}





/**
* 合並任數量的圖片成一張圖片
*
* @param isHorizontal true代表水平合並,fasle代表垂直合並
* @param imgs 待合並的圖片數組
* @return
* @throws IOException
*/
public static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) throws IOException {
// 生成新圖片
BufferedImage destImage = null;
// 計算新圖片的長和高
int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
// 獲取總長、總寬、最長、最寬
for (int i = 0; i < imgs.size(); i++) {
BufferedImage img = imgs.get(i);
allw += img.getWidth();

if (imgs.size() != i + 1) {
allh += img.getHeight() + 5;
} else {
allh += img.getHeight();
}


if (img.getWidth() > allwMax) {
allwMax = img.getWidth();
}
if (img.getHeight() > allhMax) {
allhMax = img.getHeight();
}
}
// 創建新圖片
if (isHorizontal) {
destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
} else {
destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
}
Graphics2D g2 = (Graphics2D) destImage.getGraphics();
g2.setBackground(Color.LIGHT_GRAY);
g2.clearRect(0, 0, allw, allh);
g2.setPaint(Color.RED);

// 合並所有子圖片到新圖片
int wx = 0, wy = 0;
for (int i = 0; i < imgs.size(); i++) {
BufferedImage img = imgs.get(i);
int w1 = img.getWidth();
int h1 = img.getHeight();
// 從圖片中讀取RGB
int[] ImageArrayOne = new int[w1 * h1];
// 逐行掃描圖像中各個像素的RGB到數組中
ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1);
if (isHorizontal) {
// 水平方向合並
// 設置上半部分或左半部分的RGB
destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1);
} else {
// 垂直方向合並
// 設置上半部分或左半部分的RGB
destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1);
}
wx += w1;
wy += h1 + 5;
}


return destImage;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM