PDF、视频格式缩略图获取(pdf2img)
获取pdf缩略图
导入依赖:
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.9</version>
</dependency>
代码:
/**
* 获取pdf缩略图
*
* @param path pdf绝对路径
* @return 方便minio上传的InputStream
*/
public static InputStream getPdfThumbnail(String path) {
File file = new File(path);
PDDocument doc = null;
InputStream in = null;
try {
doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
//int pageCount = doc.getNumberOfPages(); 获取pdf总页数 全转图片就要个这
//renderImageWithDPI(pageIndex,dpi) pdf页码 Windows native DPI
BufferedImage image = renderer.renderImageWithDPI(0, 300);
//BufferedImage bb = resize(bi,220,156);调整大小 会压缩质量,分辨率
in = getInputStream(image);
} catch (IOException e) {
log.error("出错了:" + e.getMessage());
e.printStackTrace();
} finally {
try {
doc.close();
} catch (IOException e) {
log.error("流关闭异常:" + e.getMessage());
e.printStackTrace();
}
}
return in;
}
转流方法:
private static InputStream getInputStream(BufferedImage image) throws IOException {
InputStream in = null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "png", os);
in = new ByteArrayInputStream(os.toByteArray());
return in;
}
获取视频格式缩略图
导入依赖:
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.7</version>
</dependency>
代码:
/**
* 截取视频第六帧的图片
* 防止视频前5帧是黑屏
* @param filePath 视频路径
* @return InputStream
*/
public static InputStream videoImage(String filePath) {
InputStream in = null;
try {
FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(filePath);
ff.start();
//getLengthInFrames() 获取视频帧数量
int ffLength = ff.getLengthInFrames();
Frame f;
int i = 0;
while (i < ffLength) {
f = ff.grabImage();
//截取第6帧
if ((i > 5) && (f.image != null)) {
in = doExecuteFrame(f);
break;
}
i++;
}
ff.stop();
} catch (FFmpegFrameGrabber.Exception e) {
e.printStackTrace();
}
return in;
}
/**
* 截取缩略图
*
* @param f Frame
*/
private static InputStream doExecuteFrame(Frame f) {
InputStream in = null;
if (null == f || null == f.image) {
return in;
}
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage bi = converter.getBufferedImage(f);
try {
in = getInputStream(bi);
} catch (IOException e) {
e.printStackTrace();
}
return in;
}