Java保存视频以及截取视频封面保存(通过Javacv的方式)
1、maven导入所需要jar包
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>1.4.2</version>
<exclusions>
<exclusion>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>opencv</artifactId>
<version>3.4.2-1.4.2</version>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>opencv</artifactId>
<version>3.4.2-1.4.2</version>
<classifier>windows-x86_64</classifier>
</dependency>
<!-- https://mvnrepository.com/artifact/org.bytedeco.javacpp-presets/ffmpeg -->
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>ffmpeg</artifactId>
<version>4.0.1-1.4.2</version>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>ffmpeg</artifactId>
<version>4.0.1-1.4.2</version>
<classifier>windows-x86_64</classifier>
</dependency>
2、
//处理前端上传视频的接口
@RequestMapping(“uploadShareVedio”)
@ResponseBody
public String uploadShareVedio(HttpServletRequest request, HttpServletResponse response,@RequestParam(“file”) MultipartFile file)
throws Exception {
try {
UUID uuid = UUID.randomUUID();
String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();
String path=“C:/xxxxxx/”+uuid+type;
File targetFile = new File(path);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
file.transferTo(targetFile);
String imgPath = "C:/xxxxxx/"+uuid+"img"+".jpg";
fetchFrame(path,imgPath);
return path+imgPath;
} catch (Exception e) {
return "0";
}
}
3、这是截图的方法
//参数:视频路径和缩略图保存路径
public static void fetchFrame(String videofile, String framefile)
throws Exception {
long start = System.currentTimeMillis();
File targetFile = new File(framefile);
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile);
ff.start();
int length = ff.getLengthInFrames();
int i = 0;
Frame f = null;
while (i < length) {
// 去掉前5帧,避免出现全黑的图片,依自己情况而定
f = ff.grabImage();
if ((i > 5) && (f.image != null)) {
break;
}
i++;
}
ImageIO.write(FrameToBufferedImage(f), "jpg", targetFile);
//ff.flush();
ff.stop();
System.out.println(System.currentTimeMillis() - start);
System.out.println("生成缩略图完成");
}
public static BufferedImage FrameToBufferedImage(Frame frame) {
//创建BufferedImage对象
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage bufferedImage = converter.getBufferedImage(frame);
return bufferedImage;
}
4、至此视频和截图都已经存在电脑当中了,真正使用时地址改为服务器地址
5、重启服务器