文章目录
- 视频生成缩略图
- 使用ffmpeg
视频生成缩略图
最近有个需求,视频上传之后在列表和详情页需要展示缩略图
使用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();
// 视频总帧数
int videoLength = ff.getLengthInFrames();
org.bytedeco.javacv.Frame f = null;
int i = 0;
while (i < videoLength) {
// 过滤前20帧,因为前20帧可能是全黑的
// 这里看需求,也可以直接根据帧数取图片
f = ff.grabFrame();
if (i > 20 && f.image != null) {
break;
}
i++;
}
int owidth = f.imageWidth;
int oheight = f.imageHeight;
// 对截取的帧进行等比例缩放
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 "";
}
参考文献
- 视频生成缩略图