需求是通过Java获取视频中的某个帧的图片,项目依赖包如下:
jar下载地址:https://pan.baidu.com/s/1LI68r6H17sAA4Pfbnpm44g
转换类:
package com.sundy.app;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
public class FileUtils {
public static void main(String[] args) throws Exception {
String videoFilePath="D:\\avifile\\test002.mp4";
String picFilePath="D:\\\\avifile\\\\test003.jpg";
fetchFrame(videoFilePath,picFilePath);
}
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) {
// 过滤前5帧,避免出现全黑的图片,依自己情况而定
f = ff.grabFrame();
if ((i > 48) && (f.image != null)) {
break;
}
i++;
}
// IplImage img = f.image;
int owidth = f.imageWidth;
int oheight = f.imageHeight;
// 对截取的帧进行等比例缩放
int width = 300;
int height = (int) (((double) width / owidth) * oheight);
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage fecthedImage = converter.getBufferedImage(f);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
0, 0, null);
ImageIO.write(bi, "jpg", targetFile);
ff.stop();
System.out.println(System.currentTimeMillis() - start);
}
}