依赖
<dependency><groupId>org.bytedeco</groupId><artifactId>javacv-platform</artifactId><version>1.5.9</version></dependency>
传入视频流获取图片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();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;}
传入视频流获取图片文件
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();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());}
