功能模块 上传视频 生成视频预览图

原文:https://www.cnblogs.com/DoNetCoder/archive/2014/11/15/4100127.html
原文:https://www.cnblogs.com/xinbaba/p/11363224.html


大致流程

通过调用ffmpeg来实现的

代码



/// <summary>
/// 测试
/// </summary>
public void test1()
{
    GetPicFromVideo("1.mp4", "1.png");
    GetPicFromVideo("2.mp4", "2.png");
}


/// <summary>
/// 生成视频的预览图
/// </summary>
/// <param name="videoFilePath"></param>
/// <param name="imgName"></param>
/// <returns></returns>
public static string GetPicFromVideo(string videoFilePath, string imgName)
{
    //string videoFilePath = "1.3gp";
    //string imgName = " 1.jpg";
    string ffmpegPath = "ffmpeg\\ffmpeg.exe";
    string cutTimeFrame = "1";
    string widthAndHeight = "";//960*540

    //得到预览图的宽高
    int width = -1;
    int height = -1;
    GetMovWidthAndHeight(ffmpegPath, videoFilePath, out width, out height);
    widthAndHeight = $"{width}*{height}";

    var startInfo = new ProcessStartInfo(ffmpegPath);
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;

    string cmd = $" -i {videoFilePath} -y -f image2 -ss {cutTimeFrame} -t 0.001 -s {widthAndHeight}  {imgName}";
    startInfo.Arguments = cmd;
    Process.Start(startInfo);

    return imgName;
}


/// <summary>
/// 获取视频的帧宽度和帧高度
/// </summary>
/// <param name="videoFilePath"></param>
/// <param name="width"></param>
/// <param name="height"></param>
public static void GetMovWidthAndHeight(string ffmpegPath, string videoFilePath, out int width, out int height)
{
    width = -1;
    height = -1;
    string output;
    string error;

    //"ffmpeg\\ffmpeg.exe" -i "1.mp4"
    string cmd = $"\"{ ffmpegPath}\" -i \"{ videoFilePath}\"";

    ExecuteCommand(cmd, out output, out error);

    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);
    }
}

/// <summary>
/// 执行一条command命令
/// </summary>
/// <param name="command">需要执行的Command</param>
/// <param name="output">输出</param>
/// <param name="error">错误</param>
public static void ExecuteCommand(string command, out string output, out string error)
{
    //创建一个进程
    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;
}


效果

猜你喜欢

转载自www.cnblogs.com/guxingy/p/12937770.html