MP4抽取图片
// 视频文件路径
String videoFilePath = "E:\\home\\video\\WeddingMarch\\base\\video\\1.mp4";
// 输出图像文件夹路径
String outputFolderPath = "E:\\home\\video\\WeddingMarch\\base\\images\\";
// 创建FFmpegFrameGrabber对象
FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoFilePath);
grabber.setFormat("mp4");
grabber.start();
// 获取视频总帧数
int totalFrames = grabber.getLengthInFrames();
// 遍历每一帧并保存为图像
for (int i = 0; i < totalFrames; i++) {
Frame frame = grabber.grabImage();
if (frame != null) {
// 将帧转换为BufferedImage对象
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage image = converter.convert(frame);
// 保存图像到文件
File outputFile = new File(outputFolderPath + "frame_(" + i + ").png");
javax.imageio.ImageIO.write(image, "png", outputFile);
}
}
// 释放资源
grabber.stop();
grabber.release();
图片集合转Mp4
imagePath处理:
Path path = Paths.get("E:\\home\\video\\WeddingMarch\\imageToMp4\\images");
List<String> imagePaths = new ArrayList<>();
long count = Files.list(path).count();
for (int i = 0; i < count; i++) {
imagePaths.add(path+"\\frame_(" + i + ").png");
}
imgToMp4(imagePaths);
转换
public static void imgToMp4(List<String> imagesPath) throws Exception{
String outputVideoPath = "E:\\home\\video\\WeddingMarch\\imageToMp4\\video\\1.mp4";
try {
convertImagesToVideo(imagesPath, outputVideoPath);
System.out.println("视频转换成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("视频转换失败!");
}
}
public static void convertImagesToVideo(List<String> imagePaths, String outputVideoPath) throws Exception {
// 创建FFmpegFrameRecorder对象
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputVideoPath, 1920, 1080);
recorder.setFormat("mp4");
recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
recorder.setFrameRate(25);
recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);
recorder.setImageWidth(2610);
recorder.setImageHeight(180);
recorder.start();
// 读取图片并转换为Frame对象
Java2DFrameConverter converter = new Java2DFrameConverter();
OpenCVFrameConverter.ToIplImage converterToIplImage = new OpenCVFrameConverter.ToIplImage();
for (String imagePath : imagePaths) {
BufferedImage image = ImageIO.read(new File(imagePath));
Frame frame = converter.convert(image);
recorder.record(frame);
}
// 释放资源
recorder.stop();
recorder.release();
}