原创

javacv获取视频第一帧

参考链接:
http://www.zuidaima.com/blog/3702403061419008.htm

①需要到jar包

    <dependency>  
       <groupId>org.bytedeco</groupId>  
       <artifactId>javacv-platform</artifactId>  
       <version>1.3.1</version>  
   </dependency>

②代码
```

import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_core.IplImage;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber.Exception;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**

  • @author xiaoqiang
  • @Description javacv获取视频第一帧图片工具类
  • @date 2019/5/8 10:38
    */
    public class FrameGrabberKit {

    public static void main(String[] args) throws Exception {

     randomGrabberFFmpegImage("http://1chalk.com/group1/M00/00/9E/rBIuClzSQHaAPClMAA5OVT6OM7w328.mp4", "F:\\test", "111");
    

    }

    /*

    • @param filePath 视频路径
    • @param targerFilePath 第一帧图片存储位置
    • @param targetFileName 图片名称
    • @throws Exception
      */
      public static void randomGrabberFFmpegImage(String filePath, String targerFilePath, String targetFileName)

       throws Exception {
      

      FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(filePath);
      ff.start();
      String rotate =ff.getVideoMetadata("rotate");
      Frame f;
      int i = 0;
      while (i <1) {

       f =ff.grabImage();
       IplImage src = null;
       if(null !=rotate &&rotate.length() > 1) {
           OpenCVFrameConverter.ToIplImage converter =new OpenCVFrameConverter.ToIplImage();
           src =converter.convert(f);
           f =converter.convert(rotate(src, Integer.valueOf(rotate)));
       }
       doExecuteFrame(f,targerFilePath,targetFileName);
       i++;
      

      }

      ff.stop();

      }

      /*

    • 旋转角度的
      */
      public static IplImage rotate(IplImage src, int angle) {
      IplImage img = IplImage.create(src.height(), src.width(), src.depth(), src.nChannels());
      opencv_core.cvTranspose(src, img);
      opencv_core.cvFlip(img, img, angle);
      return img;
      }

      public static void doExecuteFrame(Frame f, String targerFilePath, String targetFileName) {

      if (null ==f ||null ==f.image) {

       return;
      

      }
      Java2DFrameConverter converter =new Java2DFrameConverter();
      String imageMat ="jpg";
      String FileName =targerFilePath + File.separator +targetFileName +"." +imageMat;
      BufferedImage bi =converter.getBufferedImage(f);
      System.out.println("width:" + bi.getWidth());
      System.out.println("height:" + bi.getHeight());
      File output =new File(FileName);
      try {

       ImageIO.write(bi,imageMat,output);
      

      }catch (IOException e) {

       e.printStackTrace();
      

      }
      }
      }

```

正文到此结束
本文目录