1️⃣配置Maven 在pox.xml中加入
org.bytedeco
javacv-platform
1.5.7
2️⃣创建FrameExtractor
import org.bytedeco.javacv.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class FrameExtractor {
public static void main(String[] args) {
// 视频文件路径
String videoFilePath = "/Users/canna/···/XXX.mp4";//此处写自己的视频路径
// 创建FFmpegFrameGrabber对象
FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoFilePath);
try {
// 打开视频文件
grabber.start();
// 逐帧抓取视频
Frame frame;
int frameNumber = 1;
while ((frame = grabber.grabImage()) != null) {
BufferedImage bufferedImage = frameToBufferedImage(frame);
// 生成保存帧图像的文件路径
String outputFilePath = String.format("%s/frame_%05d.jpg", "/Users/canna/···/XXX", frameNumber);//此处写自己的保存路径
// 保存帧图像到文件
try {
ImageIO.write(bufferedImage, "jpg", new File(outputFilePath));
System.out.println("保存帧图像:" + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
}
frameNumber++;
}
// 关闭视频文件
grabber.stop();
} catch (org.bytedeco.javacv.FrameGrabber.Exception e) {
e.printStackTrace();
}
}
/**
* 将Frame转换为BufferedImage
*/
private static BufferedImage frameToBufferedImage(Frame frame) {
Java2DFrameConverter converter = new Java2DFrameConverter();
return converter.getBufferedImage(frame);
}
}
3️⃣运行 结果如下