引言
我们在日常工作中经常会遇到上传视频,而产品还会要求截取视频某一帧作为封面展示,对于这种情况新手还是比较头疼的,那我们直接世界上最简单的实现方案。
How to do
1.提前引入包
java
<!--视频多媒体工具包 包含 FFmpeg、OpenCV-->
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.3</version>
</dependency>
<!--hutool万能工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.4</version>
</dependency>
2.逻辑代码实现
java
public static void main(String[] args) throws IOException, InterruptedException {
Image image = cutScreenshot("");
String jpg = ImgUtil.toBase64(image, "jpg");
System.out.println(jpg);
}
/**
* 截屏视频最后一帧(有效图片)
*
* @param localPath 本地视频地址
* @return
*/
public static Image cutScreenshot(String localPath) throws FrameGrabber.Exception {
FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(localPath);
grabber.start();
// 设置帧数
grabber.setFrameNumber(grabber.getLengthInFrames() - 1);
// 获取当前有效图片(如果没有图片返回的是null,后期在做优化)
Frame frame = grabber.grabImage();
//视频旋转度
String rotate = grabber.getVideoMetadata("rotate");
Java2DFrameConverter converter = new Java2DFrameConverter();
//绘制图片
BufferedImage bufferedImage = converter.getBufferedImage(frame);
if (rotate != null) {
// 旋转图片
bufferedImage = rotate(bufferedImage, Integer.parseInt(rotate));
}
log.info("视频的宽:{}", bufferedImage.getWidth());
log.info("视频的高:{}", bufferedImage.getHeight());
log.info("视频的旋转度:{}", rotate);
log.info("视频的格式:{}", grabber.getFormat());
log.info("此视频时长(s/秒):{}", grabber.getLengthInTime() / (1000 * 1000));
return bufferedImage;
}