javacv 读取mp4,avi等视频文件并截图保存图片到本地
代码如下:
package com.example.javacvstudy;import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;import org.opencv.core.Core;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class ReadMp4 {public static void main(String[] args) {
// 加载OpenCV库System.loadLibrary(Core.NATIVE_LIBRARY_NAME);// 视频文件路径String videoPath = "D:\\down\\baozi.mp4"; // 替换为您的视频路径// 保存帧截图的文件夹路径String outputFolderPath = "D:\\temp\\img"; // 替换为您的输出文件夹路径File outputFolder = new File(outputFolderPath);outputFolder.mkdirs();// 打开视频文件try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoPath)) {grabber.start();// 遍历视频的每一帧int frameNumber = 0;Java2DFrameConverter converter = new Java2DFrameConverter();while (true) {Frame frame = grabber.grabImage();if (frame == null) {break;}// 将帧转换为BufferedImageBufferedImage image = converter.convert(frame);// 保存图片String outputFilePath = outputFolderPath + File.separator + "frame_" + frameNumber + ".jpg";File outputFile = new File(outputFilePath);ImageIO.write(image, "jpg", outputFile);frameNumber++;Thread.sleep(1000);}grabber.stop();} catch (Exception e) {e.printStackTrace();}System.out.println("帧截图保存完成!");}}
运行结果:
测试视频mp4 下载