.Net调用ffmpeg对视频截图

2019/10/27, .Net c#代码片段

摘要:借助ffmpeg对视频/图片截图、生成缩略图,使用命令行调用ffmpeg工具,支持Linux和Windows

网上很多版本都是需要等待4s的做法,这里不需要等待固定4s

添加引用对系统判断:

using System.Runtime.InteropServices;
/// 
/// 借助ffmpeg生成缩略图
/// 
/// 源文件
public void GenerateThumbnail(string originalFilePath)
{
    try
    {
        //判断系统类型
        //如果是windows,直接使用ffmpeg.exe
        //如果是linux,则使用安装的ffmpeg(需要提前安装)
        /*
          Linux工具调用:ffmpeg -i 333.jpg -q:v 31 -frames:v 1 -y image.jpg
          windows:  ffmpeg.exe -i 333.jpg -q:v 31 -frames:v 1 -y image.jpg

              -i 333.jpg 是输入文件
              -q:v 31 是质量,值区间是2-31
              -frames:v 1 是提取帧必要参数
              -y 是遇到同名文件则覆盖 
              image.jpg 输出文件名
              还可以加 -s 160*100 表示输出宽高比为160*100
         */
        string outputFilePath = "image.jpg";//输出文件
        string cmdPath = string.Empty;//ffmpeg工具对象
        string cmdParams = $" -i {originalFilePath} -q:v 31 -frames:v 1 -y {outputFilePath} ";//命令参数
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            cmdPath = "ffmpeg.exe";//根据实际的ffmpeg.exe文件路径来
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            cmdPath = "ffmpeg";//安装ffmpeg工具
        }
        else
        {
            throw new Exception("当前操作系统不支持!");
        }

        using (System.Diagnostics.Process ffmpegProcess = new System.Diagnostics.Process())
        {
            StreamReader errorReader;  // StringWriter to hold output from ffmpeg  
            // execute the process without opening a shell  
            ffmpegProcess.StartInfo.UseShellExecute = false; 
            //ffmpegProcess.StartInfo.ErrorDialog = false;  
            ffmpegProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            // redirect StandardError so we can parse it  
            ffmpegProcess.StartInfo.RedirectStandardError = true;
            // set the file name of our process, including the full path  
            // (as well as quotes, as if you were calling it from the command-line)  
            ffmpegProcess.StartInfo.FileName = cmdPath;

            // set the command-line arguments of our process, including full paths of any files  
            // (as well as quotes, as if you were passing these arguments on the command-line)  
            ffmpegProcess.StartInfo.Arguments = cmdParams;

            ffmpegProcess.Start();// start the process  

            // now that the process is started, we can redirect output to the StreamReader we defined  
            errorReader = ffmpegProcess.StandardError;

            ffmpegProcess.WaitForExit();// wait until ffmpeg comes back  

            //result = errorreader.ReadToEnd();
        }
    }
    catch (Exception ex)
    {
        throw new Exception("生成缩略图出错!", ex);
    }
}

你可能感兴趣的:(.Net调用ffmpeg对视频截图)