視頻生成縮略圖
最近有個(gè)需求,視頻上傳之后在列表和詳情頁需要展示縮略圖
使用ffmpeg
首先引入jar包
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacpp</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>ffmpeg-platform</artifactId>
<version>4.0.2-1.4.3</version>
</dependency>
代碼如下
public String getThumbnails(String videoFilePath){
String path = "/Users/zhanghe/Desktop/pic/";
String fileName = videoFilePath.substring(videoFilePath.lastIndexOf("/") + 1, videoFilePath.lastIndexOf("."))+"_thumb.jpg";
String filePath = StringUtils.join(path, fileName);
File targetFile = new File(filePath);
try {
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoFilePath);
ff.start();
// 視頻總幀數(shù)
int videoLength = ff.getLengthInFrames();
org.bytedeco.javacv.Frame f = null;
int i = 0;
while (i < videoLength) {
// 過濾前20幀,因?yàn)榍?0幀可能是全黑的
// 這里看需求,也可以直接根據(jù)幀數(shù)取圖片
f = ff.grabFrame();
if (i > 20 && f.image != null) {
break;
}
i++;
}
int owidth = f.imageWidth;
int oheight = f.imageHeight;
// 對截取的幀進(jìn)行等比例縮放
int width = 800;
int height = (int) (((double) width / owidth) * oheight);
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage fecthedImage = converter.getBufferedImage(f);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
0, 0, null);
ImageIO.write(bi, "jpg", targetFile);
ff.stop();
System.out.println(targetFile.getPath());
return targetFile.getPath();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
參考文獻(xiàn)