csharp Ffmpeg视频上传和转换,并通过asp.net获取缩略图

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp Ffmpeg视频上传和转换,并通过asp.net获取缩略图相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;

namespace HelperClass
{
    public class VideoHelper
    {
        private static List<string> videoExtension = new List<string>();
        private static string videoUploadDirectory = "";
        private static string ApplicationPath = "";
        private static string directory = "";

        public static string VideoUpload(FileUpload fu)
        {
            ApplicationPath = HttpContext.Current.Request.ApplicationPath;
            videoUploadDirectory = @"";
            if (ApplicationPath != "/")
                videoUploadDirectory += ApplicationPath + "/video";
            else
                videoUploadDirectory += "/video";
            directory = HttpContext.Current.Server.MapPath(videoUploadDirectory);
            string videoUrl = "";

            if (fu.HasFile)
            {
                string filename = fu.PostedFile.FileName;

                if (CheckExtension(fu))
                {
                    if (!System.IO.Directory.Exists(directory))
                    {
                        System.IO.DirectoryInfo di = System.IO.Directory.CreateDirectory(directory);
                        System.Security.AccessControl.DirectorySecurity diS = di.GetAccessControl();
                        di.SetAccessControl(diS);
                    }

                    try
                    {
                        string sFilePath = createRandom(filename.replace(), directory);
                        fu.SaveAs(HttpContext.Current.Server.MapPath(sFilePath));

                        // after upload get file extension and if needs convert file
                        FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath(sFilePath));
                        string _filename = Path.GetFileNameWithoutExtension(fi.Name);
                        string _extension = Path.GetExtension(fi.Name);
                        string conversionResult = string.Empty;
                        conversionResult = ConvertVideo(sFilePath, ".mp4");

                        if (conversionResult == "success")
                        {
                            videoUrl = sFilePath;
                        }
                        else
                        {
                            videoUrl = sFilePath;
                        }
                    }
                    catch (Exception ex)
                    {
                        string msg = ex.Message;
                    }
                }
                else
                {
                    return "Video format not supported!";
                }
            }

            return videoUrl;
        }

        public static bool CheckExtension(FileUpload fu)
        {
            videoExtension.Clear();
            videoExtension.Add(".flv");
            videoExtension.Add(".mp4");
            videoExtension.Add(".avi");
            videoExtension.Add(".ogv");
            videoExtension.Add(".swf");
            videoExtension.Add(".webm");
            videoExtension.Add(".wmv");
            videoExtension.Add(".mkv");

            string filename = fu.PostedFile.FileName;
            string extension = System.IO.Path.GetExtension(filename);
            if (videoExtension.Contains(extension.ToLower()))
                return true;
            else
                return false;
        }

        public static string createRandom(string filename, string directory)
        {
            Random random = new Random();
            Int32 rand = random.Next(1, 999999999);
            string newfilename = System.IO.Path.GetFileNameWithoutExtension(filename) + "___(" + rand + ")" + System.IO.Path.GetExtension(filename);
            string fileDirectory = System.IO.Path.Combine(directory, newfilename);
            if (System.IO.File.Exists(fileDirectory))
                createRandom(filename, directory);

            return videoUploadDirectory + "/" + newfilename;
        }

        #region Get screenshot from video

        /// <summary>
        /// file means video file with extension ex: video.mp4
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string GenerateThumbFromVideo(string file)
        {
            string thumbUploadDirectory = "", directory = "", ApplicationPath = "";
            string thumb = "";
            thumbUploadDirectory = @"";
            if (ApplicationPath != "/")
            {
                thumbUploadDirectory += ApplicationPath + "/video";
                file = ApplicationPath + file;
            }
            else
            {
                thumbUploadDirectory += "/video";
            }

            directory = HttpContext.Current.Server.MapPath(thumbUploadDirectory);

            try
            {
                string ffmpegFilePath = "~" + ApplicationPath + "/video/ffmpeg/ffmpeg.exe";
                FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath(file));
                string filename = Path.GetFileNameWithoutExtension(fi.Name);
                string extension = Path.GetExtension(fi.Name);
                Random random = new Random();
                int rand = random.Next(1, 9999999);
                string newfilename = "";
                if (ApplicationPath != "/")
                    newfilename = ApplicationPath + "/video/" + filename.replace() + "___(" + rand.ToString() + ").jpg";
                else
                    newfilename = "/video/" + filename.replace() + "___(" + rand.ToString() + ").jpg";

                var processInfo = new ProcessStartInfo();
                processInfo.FileName = "\"" + HttpContext.Current.Server.MapPath(ffmpegFilePath) + "\"";
                processInfo.Arguments = string.Format("-ss {0} -i {1} -f image2 -vframes 1 -y {2}", 5, "\"" + HttpContext.Current.Server.MapPath(file) + "\"", "\"" + HttpContext.Current.Server.MapPath(newfilename) + "\"");
                processInfo.CreateNoWindow = true;
                processInfo.UseShellExecute = false;
                using (var process = new Process())
                {
                    process.StartInfo = processInfo;
                    process.Start();
                    process.WaitForExit();
                    thumb = newfilename;
                }
            }
            catch (Exception ex)
            {
                string error = ex.Message;
            }

            return thumb;
        }

        #endregion Get screenshot from video

        #region Convert video (if extension is avi, wmv, mpeg or mpg you have to convert to flv or mp4 for best options)

        public static string ConvertVideo(string file, string convertedExtension)
        {
            string result = string.Empty;
            string input = string.Empty;
            string output = string.Empty;
            try
            {
                string ffmpegFilePath = "~" + ApplicationPath + "/video/ffmpeg/ffmpeg.exe";
                FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath(file));
                string filename = Path.GetFileNameWithoutExtension(fi.Name);
                string extension = Path.GetExtension(fi.Name);
                input = HttpContext.Current.Server.MapPath(file);
                output = HttpContext.Current.Server.MapPath("/video/" + filename + convertedExtension);

                //ffmpeg -i infile.avi -vcodec libx264 -vpre default -crf 21 -acodec libfaac -ab 128k output.mp4
                //var processInfo = new ProcessStartInfo(HttpContext.Current.Server.MapPath(ffmpegFilePath), " -i \"" + input + "\" -c:v libx264 -crf 18 -preset fast -c:a aac -strict experimental -b:a 192k -ac 2 -movflags faststart  \"" + output + "\"")
                //var processInfo = new ProcessStartInfo(HttpContext.Current.Server.MapPath(ffmpegFilePath), " -i \"" + input + "\" -sameq \"" + output + "\"")
                var processInfo = new ProcessStartInfo(HttpContext.Current.Server.MapPath(ffmpegFilePath), " -i \"" + input + "\" -c:v libx264 -crf 18 -preset fast -c:a aac -strict experimental -b:a 192k -ac 2 -movflags faststart  \"" + output + "\"")
                {
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true
                };

                try
                {
                    Process process = System.Diagnostics.Process.Start(processInfo);
                    result = process.StandardError.ReadToEnd();
                    process.WaitForExit();
                    process.Close();
                    result = "success";
                }
                catch (Exception ex)
                {
                    result = "error: " + ex.Message;
                }
            }
            catch (Exception ex)
            {
                result = "error: " + ex.Message;
            }

            return result;
        }

        #endregion Convert video (if extension is avi, wmv, mpeg or mpg you have to convert to flv or mp4 for best options)
    }
}

以上是关于csharp Ffmpeg视频上传和转换,并通过asp.net获取缩略图的主要内容,如果未能解决你的问题,请参考以下文章

FFmpeg的使用——PHP转换视频截取视频以及JW Player播放器控制

csharp 使用FFMPEG截取屏幕截图并从视频生成图像

如何转换上传的视频并从此文件中获取屏幕截图?

FFMPEG为视频添加圆形蒙版,转换为黑白并连接

SpringBoot + FFmpeg 进行视频分片上传实战演练

FFMPEG 转换的视频在 HTML5 中不起作用