目录
视频抽帧
1. maven依赖
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5</version>
</dependency>
2. 实例
public class CommonUtils {
private final static Logger log = LoggerFactory.getLogger(CommonUtils.class);
/**
* 视频抽帧(每second抽一帧)
* @param videoPath
* @param second
* @return
*/
public static List<String> videoFrameExtract(String videoPath, Integer second){
long start = System.currentTimeMillis();
ArrayList<String> fl = new ArrayList<>(); // 返回的抽帧图片地址
String saveFilePrefix = videoPath.substring(0, videoPath.lastIndexOf(".")); // 保存的文件名前缀
Frame frame;
FFmpegFrameGrabber ffg = null;
int fps = 0; // 帧率
long videoTime = 0L; // 视频时长
int frameCount = 0; // 视频总帧数(该视频有多少张图片)
try{
ffg = new FFmpegFrameGrabber(videoPath);
ffg.start();
fps = (int)ffg.getFrameRate();
videoTime = ffg.getLengthInTime() / (1000*1000);
while ((frame=ffg.grabImage()) != null){
if (frame.image != null){
// 获取特定帧(间隔n秒获取一帧图片)
if (frameCount>=1 && frameCount%(second*fps)==0){
// 文件保存
String fileName = saveFilePrefix + "-" + frameCount + ".jpg";
boolean saveFlag = false;
try {
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage bufferedImage = converter.getBufferedImage(frame);
saveFlag = ImageIO.write(bufferedImage, "jpg", new File(fileName));
if (saveFlag){
fl.add(fileName);
}
}catch (Exception e){
log.error("帧图片保存异常({}):{}", fileName, String.valueOf(e));
}
// log.info("帧图片保存({}):{}", fileName, saveFlag);
}
}
frameCount ++;
}
}catch (Exception e){
e.printStackTrace();
log.error("视频抽帧异常({}):{}", videoPath, String.valueOf(e));
}finally {
try {
if (ffg != null){
ffg.stop();
}
}catch (Exception ignored){}
}
long cost = System.currentTimeMillis() - start;
log.info("视频抽帧({})-帧率:{}fps;时长:{}s;总帧数:{};抽帧耗时:{}ms;抽帧数据({}):{};", videoPath, fps, videoTime, frameCount, cost, fl.size(), fl);
return fl;
}
public static void main(String[] args) {
videoFrameExtract("F:\\test\\file\\test\\a.mp4", 1);
}
}
标签:视频,videoPath,fileName,抽帧,ffg,String From: https://www.cnblogs.com/fsh19991001/p/17846968.html