Java获取网络视频封面图片

项目场景:

项目中需要根据提供的视频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");
    }

结语:

        流水争先,靠的是绵绵不绝;我们即便普通,但只要不下场,都会随着时代潮水不断向前

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值