外部插件:(http://ffmpeg.org/download.html)
FfmpegHelper.cs 文件
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Service { public static class FfmpegHelper { /// <summary> /// 从视频画面中截取一帧画面为图片 /// </summary> /// <param name="videoName">视频文件路径pic/123.MP4</param> /// <param name="cutTimeFrame">开始截取的时间如:"1s"</param> /// <param name="widthAndHeight">图片的尺寸如:240*180</param> /// <returns>返回图片保存路径</returns> public static string GetPicFromVideo(string videoName, string imageFile = "", string cutTimeFrame= "1s", string imagePath = "/CoverImage/ProjectEvent/", string widthAndHeight="") { var vdoName = videoName.Substring(videoName.LastIndexOf("/") + 1); //视频名称 例:260026077324.mp4 var fileName = vdoName.Split('.')[0];//视频名称 例:260026077324 string basePath = System.AppDomain.CurrentDomain.BaseDirectory;//获取当前路径 例:F:TT正式天台20171130TTCloudTTCloud.Website var ImgPath = basePath + imagePath.Replace("/", "\"); //建立新文件夹路径 例F:TT20171130TTCloudTTCloud.WebsiteuploadImages2020-04-20 //ffmpeg.exe路径 var ffmpeg = basePath + "\ffmpeg\ffmpeg.exe"; // 例:F:TT20171130TTCloudTTCloud.Websiteinffmpeg.exe var srcName = (File.Exists(videoName))? videoName.Replace("/", "\") : basePath + videoName.Replace("/", "\"); //视频路径 例:F:TT20171130TTCloudTTCloud.Website\Upload10000000TTVideo260026077324.mp4 if (!Directory.Exists(ImgPath)) { Directory.CreateDirectory(ImgPath); } //创建保存封面图片的路径 try { //保存截取图片后路径 var objName = ImgPath + "\" + (string.IsNullOrEmpty(imageFile)? fileName: imageFile) + ".jpg"; ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.Arguments = " -i " + srcName //视频路径 + " -y -f image2 -ss " + cutTimeFrame //设置开始获取帧的视频时间 + " -t 0.001 "//-s " + widthAndHeight //设置图片的分辨率 + " " + objName; //输出的图片文件名,路径前必须有空格 startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.FileName = ffmpeg; startInfo.WindowStyle = ProcessWindowStyle.Hidden; Process proc = new Process(); proc.StartInfo = startInfo; proc.Start(); proc.WaitForExit();//不等待完成就不调用此方法 proc.Close(); proc.Dispose(); return $"{imagePath}{fileName}.jpg"; } catch (Exception e) { return ""; } } } }
文件夹(ffmpeg)调试就放到Debug下面
如果明发到iis注意权限,windows servers 服务器注意要安装一个组件否则也切不了图
如果在发布的服务器实在找不到原因,就使用命令测试会报出问题:
d:ffmpegffmpeg.exe -i d:ffmpeg est.mp4 -y -f image2 -ss 1s -t 0.001 d:ffmpeg est.jpg