从视频画面中截取一帧画面为图片

发布时间 2023-04-03 10:17:42作者: NY、

需要借助外部插件 (http://ffmpeg.org/download.html

解压下载文件,并将该bin文件下的dll和exe文件拷贝到项目的文件夹中,使用的时候:调用该路径下的EXE即可

/// <summary>
/// 从视频画面中截取一帧画面为图片
/// </summary>
/// <param name="videoName">视频文件pic/123.MP4</param>
/// <param name="ResoucePath">保存地址</param>
/// <returns>返回图片保存路径</returns>
public string GetPicFromVideo(string videoName, string ResoucePath)
{
var vdoName = videoName.Substring(videoName.LastIndexOf("/") + 1); //视频名称 例:xxxxxxxxxxxxx.mp4
var fileName = vdoName.Split('.')[0];//视频名称 例:xxxxxxxxxxxxx
var ImgPath = ResoucePath; //封面图文件路径
//ffmpeg.exe路径
var ffmpeg = ResoucePath + "\\ffmpeg\\bin\\ffmpeg.exe"; // ffmpeg 文件路径
var srcName = ResoucePath + videoName.Replace("/", "\\"); //视频路径 例:F:\xxxxxxxxxxxxxxxx.mp4

if (!Directory.Exists(ImgPath))
{
Directory.CreateDirectory(ImgPath);
} //创建保存封面图片的路径

//保存截取图片后路径
var objName = ImgPath + "\\" + fileName + ".jpg";
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = " -i " + srcName //视频路径
+ " -y -f image2 -ss 1s" //设置开始获取帧的视频时间
+ " -t 0.001 "
+ " " + objName; //输出的图片文件名,路径前必须有空格
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.FileName = ffmpeg;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
try
{
Process proc = new Process();
proc.StartInfo = startInfo;
proc.Start();
proc.WaitForExit();//不等待完成就不调用此方法
proc.Close();
proc.Dispose();
return fileName + ".jpg";
}
catch (Exception e)
{
return e.Message;
}
}