项目场景:
项目中需要根据提供的视频URL,来选择某一帧的视频作为视频的封面图片
解决方案:使用FFMPEG工具完成取帧
第一步:将网络视频地址,转换成输入流
private static InputStream getVideoInputStream(String videoUrl)
throws IOException {
//下载网络文件
URL url = new URL(videoUrl);
//获取链接
URLConnection conn = url.openConnection();
//输入流
InputStream inStream = conn.getInputStream();
return inStream;
}
第二步:执行取帧操作
public static void getVideoCoverByUrl(String url) {
try (InputStream videoInputStream = getVideoInputStream(url)) {
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoInputStream);
ff.start();
int ffLength = ff.getLengthInFrames();
Frame f;
int i = 0;
while (i < ffLength) {
f = ff.grabFrame();
//截取第6帧
if ((i > 1) && (f.image != null)) {
executeFrame(f);
break;
}
i++;
}
ff.stop();
} catch (Exception e) {
log.error("getVideoCoverByUrl error:{}", ExceptionUtils.getMessage(e));
}
}
第三步:将获取的封面帧的文件流转成文件
private static void executeFrame(Frame frame) {
OutputStream output = null;
ByteArrayInputStream input = null;
try {
String imageSuffix = "png";
if (null == frame || null == frame.image) {
return;
}
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage bi = converter.getBufferedImage(frame);
output = new FileOutputStream("D:/cover-test.png");
ImageIO.write(bi, imageSuffix, output);
} catch (Exception e) {
log.error("executeFrame error:{}", ExceptionUtils.getMessage(e));
} finally {
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
} catch (Exception e) {
log.error("executeFrame error:{}", ExceptionUtils.getMessage(e));
}
}
}
测试示例如下:
public static void main(String[] args) {
getVideoCoverByUrl("视频URL");
}
结语:
流水争先,靠的是绵绵不绝;我们即便普通,但只要不下场,都会随着时代潮水不断向前