命令
ffmpeg -y -ss 0 -i a.mp4 -f image2 screen.png
参数说明
ffmpeg:调用ffmpeg工具,安装ffmeg的时候需要配置此命令。
-y:覆盖已有文件。
-ss:指定截图时间。格式1:hh:mm:ss(时分秒格式);格式2:.xxx(指定秒,精确到毫秒级别)。
-i a.mp4:指定输入文件,绝对路径和相对路径均可。
-f image2:强迫采用image2格式。
screen.png:指定输出文件,绝对路径和相对路径均可。
支持文件
ffmpeg支持的所有视频文件、gif文件可以执行本命令。
Java代码实现
public class FFmpegUtils {
public static boolean screenCut() throws Exception {
Process process = null;
try {
List<String> commands = new java.util.ArrayList<String>();
commands.add("ffmpeg");
commands.add("-y");
commands.add("-ss");
commands.add("0");
commands.add("-i");
commands.add("a.mp4");
commands.add("-f");
commands.add("image2");
commands.add("screen.png");
process = new ProcessBuilder(commands).redirectErrorStream(true).start();
new PrintStreamUtils(process.getErrorStream()).start();
new PrintStreamUtils(process.getInputStream()).start();
process.waitFor();
return validateInvokingFFmpeg(outputPath);
} finally {
if (null != process) {
process.destroy();
}
}
}
private static boolean validateInvokingFFmpeg(String path) {
File file = new File(path);
if (file.isFile() && file.length() > 0) {
return true;
}
return false;
}
}
class PrintStreamUtils extends Thread {
private InputStream is = null;
public PrintStreamUtils(InputStream is) {
this.is = is;
}
public void run() {
try {
while (null != is) {
if (-1 == is.read()) {
break;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (null != is) {
try {
is.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
}