0%

视频生成缩略图

视频生成缩略图

最近有个需求,视频上传之后在列表和详情页需要展示缩略图

使用ffmpeg

首先引入jar包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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>

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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 "";
}

欢迎关注我的其它发布渠道