C#讀取視頻的寬度和高度等信息的方法
本文實例講述了C#讀取視頻的寬度和高度等信息的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
讀取方式:使用ffmpeg讀取,所以需要先下載ffmpeg。網(wǎng)上資源有很多。
通過ffmpeg執(zhí)行一條CMD命令可以讀取出視頻的幀高度和幀寬度信息。
運行效果如下圖所示:
藍線框中可以看到獲取到的幀高度和幀寬度。
接下來的事情就簡單了。構造一個命令,然后執(zhí)行就ok。我并未測試過所有視頻格式,估計常見的格式應該都支持。
執(zhí)行命令的代碼如下:
/// 執(zhí)行一條command命令
/// </summary>
/// <param name="command">需要執(zhí)行的Command</param>
/// <param name="output">輸出</param>
/// <param name="error">錯誤</param>
public static void ExecuteCommand(string command,out string output,out string error)
{
try
{
//創(chuàng)建一個進程
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();
//返回流結(jié)果
output = outputData;
error = errorData;
}
catch(Exception)
{
output = null;
error = null;
}
}
獲取高度的寬度的代碼如下:(這里假設ffmpeg存在于應用程序目錄)
/// 獲取視頻的幀寬度和幀高度
/// </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;
}
//執(zhí)行命令獲取該文件的一些信息
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#程序設計有所幫助。
相關文章
C#中DataTable實現(xiàn)行列轉(zhuǎn)換的方法
這篇文章主要介紹了C#中DataTable實現(xiàn)行列轉(zhuǎn)換的方法,實例分析了C#操作DataTable的相關技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04C# HttpClient上傳文件并附帶其它參數(shù)方式
這篇文章主要介紹了C# HttpClient上傳文件并附帶其它參數(shù)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11C#利用DesignSurface如何實現(xiàn)簡單的窗體設計器
這篇文章主要介紹了C#利用DesignSurface如何實現(xiàn)簡單窗體設計器的相關資料,文中通過圖文及示例代碼介紹的很詳細,對大家具有一定的參考價值,需要的朋友們下面來一起學習學習吧。2017-02-02