主要介绍了Java获取视频时长、总帧数,并按照时间或者帧进行截图,希望对大家的学习有所帮助!
1、Maven依赖
<!--start:视频获取某一帧的图片--> <dependency> <groupId>org.bytedeco</groupId> <artifactId>javacv</artifactId> <version>1.4.3</version> </dependency> <dependency> <groupId>org.bytedeco.javacpp-presets</groupId> <artifactId>ffmpeg-platform</artifactId> <version>4.0.2-1.4.3</version> </dependency>
2、代码示例
package com.wav.utils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
/**
* @author summer
* @date 2023-10-24 15:48
*/
public class VideoToImageUtil {
public static final Logger log = LoggerFactory.getLogger(VideoToImageUtil.class);
/**
* 获取视频第一帧
*
* @param videoPath 视频地址
* @param imgPath 生成图片的名字(包含全路径)
* @throws Exception
*/
public static void getVideoPicture(String videoPath, String imgPath) throws Exception{
File imgFile = new File(imgPath);
//判断保存的文件的文件夹是否存在,不存在创建。
if (!imgFile.getParentFile().exists()) {
log.info("保存文件的文件夹不存在,创建。");
imgFile.getParentFile().mkdirs();
}
File videoFile = new File(videoPath);
if (videoFile.exists()) {
log.info("视频存在:{}", videoFile);
//实例化“截取视频首帧”对象
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoFile);
ff.start();
int width = ff.getImageWidth();
int height = ff.getImageHeight();
System.out.println("宽:" + width + ";高:" + height);
long ftp = ff.getLengthInFrames();
System.out.println("一共有:" + ftp + "帧");
// 视频帧率
double videoFrameRate = ff.getVideoFrameRate();
System.out.println("帧率:" + videoFrameRate);
long delayedTime = ff.getLengthInTime() / 1000000;
System.out.println("秒数:" + delayedTime);
int step = 5;
System.out.println("每隔:" + step + "帧取一帧");
long count = ftp / step;
for(long i = 0; i < count; i++){
System.out.println("截图进度:" + i + "/" +count);
// long time = (step * (i + 1)) * 1000000L;
// ff.setTimestamp(time);
ff.setFrameNumber((int) (step * i + 1));
Frame f = ff.grabImage();
//生成文件名称
String fileName = imgPath + "/" + i + ".jpg";
System.out.println("截图保存:" +fileName);
File out = new File(fileName);
ImageIO.write(frameToBufferedImage(f), "jpg", out);
}
ff.close();
ff.stop();
} else {
log.info("视频不存在:{}", videoFile);
}
}
/**
* 帧转为流
*
* @param frame
* @return
*/
private static RenderedImage frameToBufferedImage(Frame frame) {
//创建BufferedImage对象
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage bufferedImage = converter.getBufferedImage(frame);
return bufferedImage;
}
public static void main(String[] args) {
try {
String videoPath = "E:\\ffmpegTest\\smgnews.mp4";
String imgPath = "E:\\ffmpegTest\\img\\";
getVideoPicture(videoPath, imgPath);
} catch (Exception e) {
e.printStackTrace();
}
}
}