本文主要是介绍Java获取视频封面图,利用FFmpegFrameGrabber获取视频封面图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
依赖
<dependency><groupId>org.bytedeco</groupId><artifactId>javacv-platform</artifactId><version>1.5.9</version></dependency>
传入视频流获取图片byte
/*** 获取视频截图** @param frameNumber 视频的指定帧数* @param vName 视频名称* @param videoBytes 视频字节* @return 图片byte数组*/private byte[] getCoverImageBytes(Integer frameNumber, String vName, byte[] videoBytes) {Double videoSize = DoubleUtil.getDouble2(videoBytes.length / 1024.0 / 1024.0);long timeMillis = System.currentTimeMillis();logger.info("截取视频截图开始 视频名称:{} 视频大小:{}MB", vName, videoSize);try (ByteArrayInputStream is = new ByteArrayInputStream(videoBytes);FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(is);ByteArrayOutputStream os = new ByteArrayOutputStream();Java2DFrameConverter converter = new Java2DFrameConverter()) {grabber.start();//视频的最大帧数,减少10帧是因为最后几帧会出现获取不到图片的情况int ftp = grabber.getLengthInFrames() - 10;frameNumber = ftp < frameNumber ? ftp : frameNumber;//设置视频指定帧数grabber.setFrameNumber(frameNumber);//设置视频截取帧(默认取第一帧)Frame frame = grabber.grabImage();//绘制图片BufferedImage bi = converter.getBufferedImage(frame);ImageIO.write(bi, "jpg", os);grabber.stop();logger.info("截取视频截图结束,处理时间: {}秒", (System.currentTimeMillis() - timeMillis) / 1000);return os.toByteArray();} catch (FrameGrabber.Exception e) {logger.error("FrameGrabber.Exception :{}", e.getMessage());} catch (IOException e) {logger.error("IOException :{}", e.getMessage());}logger.info("获取视频封面图失败 vName:{}", vName);return null;}
传入视频流获取图片文件
/*** 传入视频文件,生成对应的封面图文件** @param frameNumber 帧数* @param file 视频文件*/private void coverImage(Integer frameNumber, File file) {String vName = file.getName();Double videoSize = DoubleUtil.getDouble2(file.length() / 1024.0 / 1024.0);long timeMillis = System.currentTimeMillis();logger.info("截取视频截图开始 视频名称:{} 视频大小:{}MB", vName, videoSize);try (FileInputStream is = new FileInputStream(file);FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(is);Java2DFrameConverter converter = new Java2DFrameConverter()) {grabber.start();//视频的最大帧数,减少10帧是因为最后几帧会出现获取不到图片的情况int ftp = grabber.getLengthInFrames() - 10;frameNumber = ftp < frameNumber ? ftp : frameNumber;//设置视频指定帧数grabber.setFrameNumber(frameNumber);// 图片名称String targetFileName = vName.substring(0, vName.lastIndexOf(".")) + "_vc.jpg";logger.info("图片名称:{}", targetFileName);File imageFile = new File("D:\\my_work\\" + targetFileName);//设置视频截取帧(默认取第一帧)Frame frame = grabber.grabImage();//绘制图片BufferedImage bi = converter.getBufferedImage(frame);ImageIO.write(bi, "jpg", imageFile);grabber.stop();logger.info("截取视频截图结束,处理时间: {}秒", (System.currentTimeMillis() - timeMillis) / 1000);} catch (FrameGrabber.Exception e) {logger.error("FrameGrabber.Exception :{}", e.getMessage());} catch (IOException e) {logger.error("IOException :{}", e.getMessage());}
这篇关于Java获取视频封面图,利用FFmpegFrameGrabber获取视频封面图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!