代码如下-:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
//生成视频文件的首帧为图片
//windows下的版本
public class CreatePh
{
public static boolean processImg(String veido_path, String ffmpeg_path, String min)
{
File file = new File(veido_path);
if (!file.exists())
{
System.err.println("路径[" + veido_path + "]对应的视频文件不存在!");
return false;
}
List<String> commands = new java.util.ArrayList<String>();
commands.add(ffmpeg_path);
commands.add("-i");
commands.add(veido_path);
commands.add("-y");
commands.add("-f");
commands.add("image2");
commands.add("-ss");
commands.add(min);// 这个参数是设置截取视频多少秒时的画面
// commands.add("-t");
// commands.add("0.001");
commands.add("-s");
commands.add("640x360");
System.out.println("图片地址:" + veido_path.substring(0, veido_path.lastIndexOf(".")).replaceFirst("vedio", "file") + ".jpg");
commands.add(veido_path.substring(0, veido_path.lastIndexOf(".")).replaceFirst("vedio", "file") + ".jpg");
// commands.add("C:\\Users\\Administrator\\Desktop\\ffmpeg截取图片\\" + System.currentTimeMillis() + ".jpg"); 本地路径
try
{
ProcessBuilder builder = new ProcessBuilder();
builder.command(commands);
builder.start();
System.out.println(veido_path + "视频截取成功");
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
/**
* 递归所有视频
* @author Liuxp
* @param f
* @param pathList
*/
private static void count(File f, List<String> pathList)
{
File[] list = f.listFiles();
for (File i : list)
{
boolean matches = i.getName().toLowerCase().matches(".+\\.(mp4|avi|rmvb|mpg|wmv|asf|asx|rm|rmvb|mpeg|mpe|m4v|mkv|dat|flv|vob|3gp)");
// System.out.println(matches);
if (matches == true)
{
pathList.add(i.getPath());
}
else if (i.isDirectory())
{
count(i, pathList);
}
}
}
public static void main(String[] args)
{
System.out.print("请输入文件夹路径:");
Scanner sc = new Scanner(System.in);
String next = sc.next();
// String next = "C:\\\\Users\\\\Administrator\\\\Desktop\\\\音视频";
// next = "D:\\steam\\steamapps";
// System.out.print("请输入ffmpeg路径:");
// Scanner ffmpegScanner = new Scanner(System.in);
// String ffmpeg = ffmpegScanner.next();
String ffmpeg = "Y:\\smart-edu\\ffmpeg-2022-06-27\\bin\\ffmpeg.exe";
System.out.print("请输入截取视频X秒位置:");
Scanner indexMin = new Scanner(System.in);
String min = indexMin.next();
File f = new File(next);
if (!f.isDirectory())
{
System.out.println("文件夹路径错误");
return;
}
List<String> pathList = new ArrayList<>();
count(f, pathList);
if (pathList.size() <= 0)
{
System.out.println("该文件夹未找到视频文件");
}
Integer num = 0;
for (String string : pathList)
{
processImg(string, ffmpeg, min);
num++;
}
System.out.println("共截取:" + num + " 个视频图片");
}
}
去掉package包路径使用cmd命令编译为.class文件 utf-8编译
命令:javac -encoding utf-8 CreatePh.java
执行.class文件
命令:java CreatePh #不要带后缀
效果如下
会在同目录同位置生成一个文件名一样的照片格式的文件