pom.xml
<dependency> <groupId>org.bytedeco</groupId> <artifactId>javacv</artifactId> <version>0.8</version> </dependency>
1.截取视频资源的缩略图
/**
* 获取指定视频的帧并保存为图片至指定目录
* @param videofile 源视频文件路径 例:http://ip:port/Alias0/HardDisk1/recordfiles/2018/02/02/20180202_115950_0010_B2_H.mp4
* @param framefile 截取帧的图片存放路径 例:F:\hfkjrecorder\target\4.jpg
* @throws Exception
*/
public static void fetchFrame(String videofile, String framefile)
throws Exception {
long start = System.currentTimeMillis();
File targetFile = new File(framefile);
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile);
ff.start();
int lenght = ff.getLengthInFrames();
int i = 0;
Frame f = null;
while (i < lenght) {
// 过滤前10帧,避免出现全黑的图片,依自己情况而定
f = ff.grabFrame();
if ((i > 10) && (f.image != null)) {
break;
}
i++;
}
opencv_core.IplImage img = f.image;
int owidth = img.width();
int oheight = img.height();
// 对截取的帧进行等比例缩放
int width = 800;
int height = (int) (((double) width / owidth) * oheight);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawImage(f.image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
0, 0, null);
ImageIO.write(bi, "jpg", targetFile);
//ff.flush();
ff.stop();
System.out.println(System.currentTimeMillis() - start);
}
参考:https://blog.csdn.net/syz_mumu/article/details/77203247
2.通过摄像头获取图片
/**
* 获取指定摄像头画面保存为图片至指定目录
* @param videofile 源视频文件路径 例:rtmp:ip:port/live/H1
* @param framefile 截取帧的图片存放路径 例:F:\hfkjrecorder\target\4.jpg
* @throws Exception
*/
public static void onlineFrame(String videofile, String framefile)
throws Exception {
//OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0); 本地摄像头
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(videofile);
grabber.start(); //开始获取摄像头数据
opencv_core.IplImage image =grabber.grab(); //将所获取摄像头数据放入IplImage
int owidth = image.width();
int oheight = image.height();
// 对截取的帧进行等比例缩放
int width = 800;
int height = (int) (((double) width / owidth) * oheight);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawImage(image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
0, 0, null);
ImageIO.write(bi, "jpg", new File(framefile));
cvReleaseImage(image);
grabber.stop();
}
参考:https://blog.csdn.net/sivyer123/article/details/22411861
过程:实现这两个小功能所用的javacv版本较低,在用最新版本的时候,获取视频资源缩略图过程中,如果视频资源过大会报错,我也不知道什么原因。。。在获取摄像头资源的时候,最新版本也会在获取摄像头数据时候报错,只有在用低版本(0.8)我才没有报错,达到自己所要的效果