如何通过java获取视频宽高

如何通过java获取视频宽高

摘要

如何通过java获取视频宽高

参考

https://github.com/daodaovps/testgetVideoMeta

没什么好说的,就是cmd执行exe文件获取videometa

code

package testgetVideoMeta;

import org.nutz.json.Json;
import org.nutz.lang.Strings;

import java.util.Arrays;

/**
 * Created by zsl on 2017/7/26.
 */
public class VieoHeightWidthTEST {

    /**
     * 测试   获取视频文件的宽高
     * <p>
     * http://www.javacreed.com/how-to-retrieve-the-video-properties/
     *
     * @param args
     */
    public static void main(String[] args) {

        String[] wh = getVideoFileWH("M:\\#音乐# 不一样的美丽少女萝莉.mp4");
        System.out.println(Json.toJson(wh));

    }

    private static String[] getVideoFileWH(String filepath) {
        String out = getVideoFileMeta(filepath);
        String[] arr = Strings.splitIgnoreBlank(out, "\n");

        String width = "0";
        String height = "0";
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].toLowerCase().indexOf("width") >= 0) {
                width = arr[i].toLowerCase().trim().replaceAll(" ","").replace("width", "").replace(":", "").replace("pixels", "");
                width = Strings.trim(width);
            }
            if (arr[i].toLowerCase().indexOf("height") >= 0) {
                height = arr[i].toLowerCase().trim().replaceAll(" ","").replace("height", "").replace(":", "").replace("pixels", "");
                height = Strings.trim(height);
            }
        }
        System.out.println(filepath);
        System.out.println("width " + width);
        System.out.println("height " + height);

        String[] wh = new String[2];
        wh[0] = width;
        wh[1] = height;
        return wh;
    }


    /**
     * 不抛出异常,异常作为参数包装起来
     */
    private static String getVideoFileMeta(String filepath) {
        try {

            String rs = Shell.getCmdResult("M:\\SnapShow\\MediaInfo_CLI_0.7.97_Windows_x64\\MediaInfo.exe",
                    Arrays.asList(filepath));
            return rs;

        } catch (Exception e) {
            e.printStackTrace();
        }

        throw new RuntimeException("nothing");


    }


}

Shell.java

package testgetVideoMeta;

import org.apache.commons.exec.*;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * Created by zsl on 2017/7/18.
 */
public class Shell {

    private static final Logger log = LoggerFactory.getLogger(Shell.class);


    /**
     * 超时1分钟 , 停止解析.  直接返回空
     *
     * @param cmd
     * @return
     */
    public static String getCmdResult(String cmd ,List<String> params) {

        try {

            log.info("cmd  {}" ,cmd);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();

            CommandLine cmdLine = new CommandLine(cmd);
            if(!Lang.isEmpty(params))
            {
                for (int i = 0; i < params.size(); i++) {
                    cmdLine.addArgument(params.get(i), false);
                }
            }

            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
            Executor executor = new DefaultExecutor();
//            executor.setWorkingDirectory(new File(System.getProperty("user.home")));
//            executor.setExitValue(0);
            executor.setWatchdog(watchdog);

            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
            executor.setStreamHandler(streamHandler);

            executor.execute(cmdLine, resultHandler);

            // some time later the result handler callback was invoked so we
            // can safely request the exit value
            resultHandler.waitFor();
            int exitValue = resultHandler.getExitValue();
            Exception e = resultHandler.getException();

            String out = outputStream.toString("UTF8");
            String error = errorStream.toString("UTF8");
            System.out.println("out \n" + out);
            System.out.println("error \n" + error);

            System.out.println("exitValue " + exitValue);
            System.out.println("Exception " + (e == null ? "empty" : e.getMessage()));

            if (!Strings.isBlank(error) || !Lang.isEmpty(e)) {
                log.error(error);
                log.error(Lang.getStackTrace(e));
                throw  new RuntimeException(e);
            }

            return out+"\r\n" ;

        } catch (Exception e) {
            e.printStackTrace();
            log.error(Lang.getStackTrace(e));
        }

        return "";

    }
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>testgetVideoMeta</groupId>
  <artifactId>testgetVideoMeta</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>testgetVideoMeta</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>


    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
      <version>1.5.4.RELEASE</version>
    </dependency>


    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.nutz</groupId>
      <artifactId>nutz</artifactId>
      <version>1.r.62</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-exec</artifactId>
      <version>1.3</version>
    </dependency>

  </dependencies>
</project>

MediaInfo.exe

跨平台,多个系统下都可以执行

https://mediaarea.net/en/MediaInfo/Download

相关git https://github.com/javacreed/how-to-retrieve-the-video-properties