package com.ai.runner.dmp.util;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import javax.imageio.ImageIO;
import org.bytedeco.javacpp.opencv_core.IplImage;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
/**
* FfmpegUtil <br>
* Date: 2017-10-19 上午 10:55 <br>
* Copyright (c) 2017 asiainfo.com <br>
*
* @author xuyw
*/
public class FfmpegUtil {
static{
}
/**
* 获取视频缩略图
* @param videoRealPath
* @param imagePath
* @param imageName
* @return
*/
public static boolean createThumbnail(String videoRealPath,
String imageRealPath) {
List<String> commend = new java.util.ArrayList<String>();
commend.add("D:\\tool\\ffmpeg\\ffmpeg.exe");
commend.add("-i");
commend.add(videoRealPath);
commend.add("-y");
commend.add("-f");
commend.add("image2");
commend.add("-t");
commend.add("0.011");
commend.add("-s");
commend.add("350*240");
commend.add(imageRealPath);
boolean isSuccess = true;
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process process = builder.start();
InputStream in = process.getInputStream();
byte[] re = new byte[1024];
while (in.read(re) != -1) {
}
in.close();
} catch (Exception e) {
isSuccess = false;
e.printStackTrace();
}
return isSuccess;
}
/**
* 获取指定视频的帧并保存为图片至指定目录
* @param videofile 源视频文件路径
* @param framefile 截取帧的图片存放路径
* @throws Exception
*/
public static void fetchFrame(String videofile, String framefile)
throws Exception {
long start = System.currentTimeMillis();
File targetFile = new File(framefile);
FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videofile);
ff.start();
int lenght = ff.getLengthInFrames();
int i = 0;
Frame f = null;
while (i < lenght) {
// 过滤前5帧,避免出现全黑的图片,依自己情况而定
f = ff.grabFrame();
if ((i > 130) && (f.image != null)) {
break;
}
i++;
}
IplImage img = f.image;
int owidth = img.width();
int oheight = img.height();
// 对截取的帧进行等比例缩放
int width = 350;
int height = (int) (((double) width / owidth) * oheight);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawImage(f.image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
0, 0, null);
ImageIO.write(bi, "jpg", targetFile);
//ff.flush();
ff.stop();
System.out.println(System.currentTimeMillis() - start);
}
public static void main(String[] args) throws Exception {
String videoRealPath = "D:\\4d70eff7c1f3402e9341dbbd3d1b665c.mp4";
String imagePath = "D:\\test\\"+ UUID.randomUUID().toString() + ".jpg";
FfmpegUtil.fetchFrame(videoRealPath,imagePath);
//System.out.println(System.getenv("java.library.path"));
imagePath = "D:\\test\\"+ UUID.randomUUID().toString() + ".jpg";
FfmpegUtil.createThumbnail(videoRealPath,imagePath);
}
}
Ffmpeg demo
最新推荐文章于 2024-10-21 16:08:37 发布