视频截图/分辨率/时长ffmpeg.exe的用法

 获取视频第一秒图片

public string CatchImg(string FileName, string oldimg,int GroupId)
        {
            string imgpath = "";
            string trueimgpath = "";
            imgpath = Server.MapPath("\\InfoReleaseResources\\Image\\" + GroupId + "\\");
            trueimgpath = "InfoReleaseResources/Image/" + GroupId + "/";
            if (!Directory.Exists(imgpath))
            {
                Directory.CreateDirectory(imgpath);
            }
            //取得ffmpeg.exe的路径
            string ffmpeg = System.Web.HttpContext.Current.Server.MapPath("~/ffmpeg/ffmpeg.exe");//"D:/bbbbb/ffmpeg.exe";
            string vFileName = System.Web.HttpContext.Current.Server.MapPath("~/"  + FileName);
            if ((!System.IO.File.Exists(ffmpeg)) || (!System.IO.File.Exists(vFileName)))
            {
                return "";
            }
            //获得图片相对路径/最后存储到数据库的路径,如:/InfoReleaseResources/Image/分组/图片.jpg

            string flv_img = oldimg == "" ? Path.ChangeExtension("/" + (FileName.Replace("Video", "Image").Substring(0, 27)+ GroupId + "/"+ Guid.NewGuid().ToString()), ".jpg") : oldimg;
            //图片绝对路径,如:D:\Video\Web\FlvFile\User1\0001.jpg
            string flv_img_p = System.Web.HttpContext.Current.Server.MapPath(flv_img);
            //截图的尺寸大小
            int? width, height;
            GetMovWidthAndHeight(vFileName, out width, out height);
            string FlvImgSize = width + "x" + height;
            ProcessStartInfo startInfo = new ProcessStartInfo(ffmpeg);
            startInfo.UseShellExecute = false; // 要获取输出,此值必须为 false。
            startInfo.CreateNoWindow = true;
            //startInfo.RedirectStandardResult = true;
            startInfo.RedirectStandardError = true;
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            //此处组合成ffmpeg.exe文件需要的参数即可,此处命令在ffmpeg 0.4.9调试通过 
            startInfo.Arguments = string.Format("-i \"{0}\" -ss {1} -vframes 1 -r 1 -ac 1 -ab 2 -s {2}*{3} -f image2 \"{4}\"", vFileName, 1, width, height, flv_img_p);
            try
            {
                //Process.Start(startInfo);
                //string result= process.StandardError.ReadToEnd();
                Process process = Process.Start(startInfo);
                string result = process.StandardError.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }
            catch
            {
                return "";
            }

            ///注意:图片截取成功后,数据由内存缓存写到磁盘需要时间较长,大概在3,4秒甚至更长;
            ///这儿需要延时后再检测,我服务器延时8秒,即如果超过8秒图片仍不存在,认为截图失败;
            ///此处略去延时代码.如有那位知道如何捕捉ffmpeg.exe截图失败消息,请告知,先谢过!
            //if (System.IO.File.Exists(flv_img_p))
            //{
            //    return flv_img;
            //}

            return flv_img;
        }

以上获取视频第一帧,所使用的【ffmpeg.exe】的版本是:

FFmpeg version SVN-r25512, Copyright (c) 2000-2010 the FFmpeg developers

查看自己的【ffmpeg.exe】方法:进入到该文件所在文件夹,在地址栏输入cmd回车,键入【ffmpeg.exe -version】就能查看版本了

【2021-12-14】今日有个新需求,上传视频类型添加mov格式,用此方法获取第一帧,是获取不到的;

于是在网上各种搜索【获取视频第一帧图片命令】语句,直接exe执行要么报错,要么就是生成的文件0KB损坏,官网也不是看太懂,最终抱着试试的态度,更换了【ffmpeg.exe】的版本,现在我是用的是版本:

ffmpeg version n4.4.1-2-gcc33e73618-20211212 Copyright (c) 2000-2021 the FFmpeg developers

然后更换了代码:

 startInfo.Arguments = " -i " + vFileName + " -y -f image2 -ss " + 1 + " -t 0.001 -s " + FlvImgSize + " " + flv_img_p;

【ffmpeg.exe】官方下载地址:Releases · BtbN/FFmpeg-Builds · GitHub

获取视频分辨率 

 public static void GetMovWidthAndHeight(string videoFilePath, out int? width, out int? height)
        {
            try
            {
                //判断文件是否存在
                if (!System.IO.File.Exists(videoFilePath))
                {
                    width = null;
                    height = null;
                }

                //执行命令获取该文件的一些信息 
                string ffmpegPath = System.Web.HttpContext.Current.Server.MapPath("~/ffmpeg/ffmpeg.exe");

                string output;
                string error;
                ExecuteCommand("\"" + ffmpegPath + "\"" + " -i " + "\"" + videoFilePath + "\"", out output, out error);
                if (string.IsNullOrEmpty(error))
                {
                    width = null;
                    height = null;
                }

                //string result = process.StandardError.ReadToEnd(); // 注意,是:StandardError。
                //通过正则表达式获取信息里面的宽度信息
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("(\\d{2,4})x(\\d{2,4})", System.Text.RegularExpressions.RegexOptions.Compiled);
                System.Text.RegularExpressions.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;
            }
        }

获取视频时长

public string Fromffmpeg(string fileName)
        {
            string duration = "";
            using (Process pro = new Process())
            {
                pro.StartInfo.UseShellExecute = false;
                pro.StartInfo.ErrorDialog = false;
                pro.StartInfo.RedirectStandardError = true;

                pro.StartInfo.FileName = System.Web.HttpContext.Current.Server.MapPath("~/ffmpeg/ffmpeg.exe");
                pro.StartInfo.Arguments = " -i " + System.Web.HttpContext.Current.Server.MapPath(fileName);

                pro.Start();
                System.IO.StreamReader errorreader = pro.StandardError;
                pro.WaitForExit(1000);

                string result = errorreader.ReadToEnd();
                if (!string.IsNullOrEmpty(result))
                {
                    result = result.Substring(result.IndexOf("Duration: ") + ("Duration: ").Length, ("00:00:00").Length);
                    duration = result;
                }
                return duration;

            }
        }

执行一条Command命令 

/// <summary>
        /// 执行一条command命令
        /// </summary>
        /// <param name="command">需要执行的Command</param>
        /// <param name="output">输出</param>
        /// <param name="error">错误</param>
        [LoginAjaxJson]
        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 ex)
            {
                output = null;
                error = null;
            }
        }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值