栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

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

运行效果如下图所示:

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

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

执行命令的代码如下:
复制代码 代码如下:///


/// 执行一条command命令
///

/// 需要执行的Command
/// 输出
/// 错误
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存在于应用程序目录)
复制代码 代码如下:///


/// 获取视频的帧宽度和帧高度
///

/// mov文件的路径
/// null表示获取宽度或高度失败
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#程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/125873.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号