当前位置: 移动技术网 > IT编程>开发语言>c# > C#读取视频的宽度和高度等信息的方法

C#读取视频的宽度和高度等信息的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#读取视频的宽度和高度等信息的方法。分享给大家供大家参考。具体实现方法如下:

读取方式:使用ffmpeg读取,所以需要先下载ffmpeg。网上资源有很多。

通过ffmpeg执行一条cmd命令可以读取出视频的帧高度和帧宽度信息。

运行效果如下图所示:

蓝线框中可以看到获取到的帧高度和帧宽度。

接下来的事情就简单了。构造一个命令,然后执行就ok。我并未测试过所有视频格式,估计常见的格式应该都支持。

执行命令的代码如下:

复制代码 代码如下:
/// <summary>
/// 执行一条command命令
/// </summary>
/// <param name="command">需要执行的command</param>
/// <param name="output">输出</param>
/// <param name="error">错误</param>
public static void executecommand(string command,out string output,out string error)
{
    try
    {
 //创建一个进程
 process pc = new process();
 pc.startinfo.filename = command;
 pc.startinfo.useshellexecute = false;
 pc.startinfo.redirectstandardoutput = true;
 pc.startinfo.redirectstandarderror = true;
 pc.startinfo.createnowindow = true;

 //启动进程
 pc.start();

 //准备读出输出流和错误流
 string outputdata = string.empty;
 string errordata = string.empty;
 pc.beginoutputreadline();
 pc.beginerrorreadline();
 
 pc.outputdatareceived += (ss, ee) =>
     {
  outputdata += ee.data;
     };

 pc.errordatareceived += (ss, ee) =>
     {
  errordata += ee.data;
     };
 
 //等待退出
 pc.waitforexit();

 //关闭进程
 pc.close();

 //返回流结果
 output = outputdata;
 error = errordata;
    }
    catch(exception)
    {
 output = null;
 error = null;
    }
}

获取高度的宽度的代码如下:(这里假设ffmpeg存在于应用程序目录)

复制代码 代码如下:
/// <summary>
/// 获取视频的帧宽度和帧高度
/// </summary>
/// <param name="videofilepath">mov文件的路径</param>
/// <returns>null表示获取宽度或高度失败</returns>
public static void getmovwidthandheight(string videofilepath, out int? width, out int? height)
{
    try
    {
 //判断文件是否存在
 if (!file.exists(videofilepath))
 {
     width = null;
     height = null;
 }

 //执行命令获取该文件的一些信息
 string ffmpegpath = new fileinfo(process.getcurrentprocess().mainmodule.filename).directoryname + @"\ffmpeg.exe";

 string output;
 string error;
 helpers.executecommand("\"" + ffmpegpath + "\"" + " -i " + "\"" + videofilepath + "\"",out output,out error);
 if(string.isnullorempty(error))
 {
     width = null;
     height = null;
 }

 //通过正则表达式获取信息里面的宽度信息
 regex regex = new regex("(\\d{2,4})x(\\d{2,4})", regexoptions.compiled);
 match m = regex.match(error);
 if (m.success)
 {
     width = int.parse(m.groups[1].value);
     height = int.parse(m.groups[2].value);
 }
 else
 {
     width = null;
     height = null;
 }
    }
    catch (exception)
    {
 width = null;
 height = null;
    }
}

希望本文所述对大家的c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网