maven依赖
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>1.3.1</version>
</dependency>
Java代码
public class VideoImageUntil {
private static final String IMAGEMAT = "png";
private static final String ROTATE = "rotate";
public static final int MOD = 2;//默认截取视频的中间帧为封面
public static void main(String[] args) throws Exception {
System.out.println(randomGrabberFFmpegImage("D:/1.mp4", 2));
}
/**
* 获取视频缩略图
* @param filePath:视频路径
* @param mod:视频长度/mod获取第几帧
* @throws Exception
*/
public static String randomGrabberFFmpegImage(String filePath, int mod) throws FrameGrabber.Exception {
String targetFilePath = "";
try (FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(filePath)) {
ff.start();
String rotate = ff.getVideoMetadata(ROTATE);
int ffLength = ff.getLengthInFrames();
Frame f;
int i = 0;
int index = ffLength / mod;
while (i < ffLength) {
f = ff.grabImage();
if (i == index) {
if (null != rotate && rotate.length() > 1) {
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
opencv_core.IplImage src = converter.convert(f);
f = converter.convert(rotate(src, Integer.valueOf(rotate)));
}
targetFilePath = getImagePath(filePath, i);
doExecuteFrame(f, targetFilePath);
break;
}
i++;
}
ff.stop();
}
return targetFilePath;
}
/**
* 根据视频路径生成缩略图存放路径
* @param filePath:视频路径
* @param index:第几帧
* @return:缩略图的存放路径
*/
private static String getImagePath(String filePath, int index){
if(filePath.contains(".") && filePath.lastIndexOf(".") < filePath.length() - 1){
filePath = filePath.substring(0, filePath.lastIndexOf(".")).concat("_").concat(String.valueOf(index)).concat(".").concat(IMAGEMAT);
}
return filePath;
}
/**
* 旋转图片
* @param src
* @param angle
* @return
*/
public static opencv_core.IplImage rotate(opencv_core.IplImage src, int angle) {
opencv_core.IplImage img = opencv_core.IplImage.create(src.height(), src.width(), src.depth(), src.nChannels());
opencv_core.cvTranspose(src, img);
opencv_core.cvFlip(img, img, angle);
return img;
}
/**
* 截取缩略图
* @param f
* @param targerFilePath:封面图片
*/
public static void doExecuteFrame(Frame f, String targerFilePath) {
if (null == f || null == f.image) {
return;
}
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage bi = converter.getBufferedImage(f);
File output = new File(targerFilePath);
try {
ImageIO.write(bi, IMAGEMAT, output);
//需要进行压缩图片处理
} catch (IOException e) {
e.printStackTrace();
}
}
}