The first step is to parse the video file
private static String processVideo(String filePath) {
List<String> commend=new java.util.ArrayList<String>();
commend.add("ffmpeg");// You can set environment variables to save this line//d:\ffmpeg\ffmpeg.exe
commend.add("-i");
commend.add(filePath);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process p= builder.start();
BufferedReader buf = null; // Save the output stream of ffmpeg
String line = null;
buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuffer sb= new StringBuffer();
while ((line = buf.readLine()) != null) {
sb.append(line);
continue;
}
p.waitFor();//The thread is blocked here, and it will wait for the external conversion process to run successfully before it goes down.
return sb.toString();
} catch (Exception e) {
System.out.println("ffmpeg failed to parse the video file [" + filePath +"]!");
return null;
}
}
The second step, get the relevant metadata, get the rotation angle of the video
private static String getRotate() { String rotate = ""; String result = processVideo(videoPath); System.out.println(result); if(StringUtils.isNotEmpty(result)){ PatternCompiler compiler =new Perl5Compiler(); try { String regexRotate ="rotate\\s*:\\s*(\\w*)\\s*"; Pattern patternRotate = compiler.compile(regexRotate, Perl5Compiler.CASE_INSENSITIVE_MASK); PatternMatcher matcherRotate = new Perl5Matcher(); if(matcherRotate.contains(result, patternRotate)){ MatchResult re = matcherRotate.getMatch(); rotate = re.group(1); System.out.println("rotate:"+rotate); } } catch (MalformedPatternException e) { System.out.println("Get [" + videoPath +"] video information failed!"); } System.out.println("Get [" + videoPath +"] video information successfully!"); }else{ System.out.println("Successful execution! But [" + videoPath +"] video information was not obtained!"); } return rotate; }
The third step is to call the rotation command according to the rotate angle information
private static boolean rotate90mp4(String rotate) { List<String> commend = new ArrayList<String>(); //ffmpeg -i demo.mp4 -vf "transpose=1" o.mp4 try { Runtime runtime = Runtime.getRuntime(); // String cmd = " ffmpeg -i "+ videoPath + " -vf \"transpose=1\" d:\\out\\vertical.mp4"; StringBuffer buf = new StringBuffer(); buf.append(" ffmpeg "); buf.append(" -i "); buf.append(videoPath); if(!StringUtils.isBlank(rotate)){ buf.append(" -vf "); if(rotate.equals("90")) buf.append(" \"transpose=1\" "); else if(rotate.equals("180")) buf.append(" \"transpose=2,transpose=2\" "); else if(rotate.equals("270")) buf.append(" \"transpose=2\" "); } buf.append(destPath); runtime.exec(buf.toString()); return true; } catch (Exception e) { e.printStackTrace (); return false; } }