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>
代码:
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) ;
BufferedImage image = renderer. renderImageWithDPI ( 0 , 300 ) ;
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>
代码:
public static InputStream videoImage ( String filePath) {
InputStream in = null ;
try {
FFmpegFrameGrabber ff = FFmpegFrameGrabber . createDefault ( filePath) ;
ff. start ( ) ;
int ffLength = ff. getLengthInFrames ( ) ;
Frame f;
int i = 0 ;
while ( i < ffLength) {
f = ff. grabImage ( ) ;
if ( ( i > 5 ) && ( f. image != null ) ) {
in = doExecuteFrame ( f) ;
break ;
}
i++ ;
}
ff. stop ( ) ;
} catch ( FFmpegFrameGrabber. Exception e) {
e. printStackTrace ( ) ;
}
return in;
}
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;
}
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· RFID实践——.NET IoT程序读取高频RFID卡/标签