这篇文章介绍一种在Java中为视频生成缩略图的方式,借助的工具是ffmpeg。
具体实现代码:
/**
* 从视频中每X秒创建一个缩略图
*
* @param videoPath 视频文件完整路径
* @param picSavePath 缩略图保存完整路径
* @param yyyyMMddHHmmss 截图时间
* @param picNumPerSecond 每秒几张图(例如:1表示每秒一张;1/60表示一分钟一张;1/600表示10分钟一张)
*/
public void createVideoThumbnail(String videoPath, String picSavePath, String yyyyMMddHHmmss, String picNumPerSecond) {
//String ffmpegPath = PropsUtil.getProperty("ffmpeg_path");
String ffmpegPath = "D:/epcp/javaffmpeg/FFmpeg/bin/ffmpeg.exe";
//如果picSavePath不以文件分隔符结尾,自动添加文件分隔符
if (!picSavePath.endsWith(File.separator)) {
picSavePath = picSavePath + File.separator;
}
List<String> command = new ArrayList<String>();
command.add(ffmpegPath);
command.add("-i");
command.add(videoPath);
command.add("-vf");
command.add("fps=" + picNumPerSecond);
command.add(picSavePath + yyyyMMddHHmmss + "_%d.png");
try {
ProcessBuilder builder = new ProcessBuilder(command);
builder.command(command);
Process p = builder.start();
p.waitFor();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
public static int doWaitFor(Process process) {
int exitValue = -1; // returned to caller when p is finished
InputStream error = process.getErrorStream();
InputStream is = process.getInputStream();
byte[] b = new byte[1024];
int readbytes = -1;
try {
while ((readbytes = error.read(b)) != -1) {
logger.info("进程信息:" + new String(b, 0, readbytes));
}
while ((readbytes = is.read(b)) != -1) {
logger.info("进程输出内容为:" + new String(b, 0, readbytes));
}
} catch (IOException e) {
logger.error("等待进程结束出现错误!");
e.printStackTrace();
} finally {
try {
error.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return exitValue;
}
参考文章: