欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

给上传的文件生成缩略图(图片和视频)

程序员文章站 2022-06-02 21:17:30
...
备注:里面用到的ffmpeg可在https://ffmpeg.zeranoe.com/builds/ 下载


1、根据视频,生成截图
#region 从视频画面中截取一帧画面为图片
        /// <summary>
        /// 从视频画面中截取一帧画面为图片
        /// </summary>
        /// <param name="VideoName">视频文件,绝对路径</param>
        /// <param name="WidthAndHeight">图片的尺寸如:240*180</param>
        /// <param name="CutTimeFrame">开始截取的时间如:"1"</param>
        /// <returns></returns>
        public static string GetPicFromVideo(string VideoName, string WidthAndHeight, string CutTimeFrame)
        {
            //ffmpeg执行文件的路径
            string ffmpeg = System.AppDomain.CurrentDomain.BaseDirectory + "ffmpeg\\ffmpeg.exe";
            string PicName = VideoName + ".jpg";//视频图片的名字,绝对路径
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.Arguments = " -i " + VideoName
                                + " -y -f image2 -ss " + CutTimeFrame
                                + " -t 0.001 -s " + WidthAndHeight
                                + " " + PicName;  //設定程式執行參數
            try
            {
                System.Diagnostics.Process.Start(startInfo);
                Thread.Sleep(5000);//线程挂起,等待ffmpeg截图完毕
            }
            catch (Exception e)
            {
                return e.Message;
            }

            //返回视频图片完整路径
            if (System.IO.File.Exists(PicName))
                return PicName;
            return "";
        }
        #endregion


2、图片压缩并保存GetPicThumbnail
#region 图片压缩并保存GetPicThumbnail
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原文件位置</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="flag">压缩比例,eg:按照百分比算如80,就是原图的高度乘以80%</param>
        /// <returns></returns>
        public static bool GetPicThumbnail(string sFile, string dFile, int flag)
        {
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            int dHeight = iSource.Height * flag / 100; //高度压缩百分不
            int dWidth = iSource.Width * flag / 100;//宽度压缩百分比
            if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号
            {
                if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);
            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时,设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();

                ImageCodecInfo jpegICIinfo = null;

                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();

            }
        }
        #endregion



3、循环文件夹中的所有文件,生成对应的压缩图片   需要用到循环调用
先调用获取目录下所有文件夹的方法,此方法中调用了getFileName方法,也调用了自己,可实现循环遍历直到把所有文件都执行一边

#region 获取指定路径下所有文件名
        /// <summary>
        /// 获得指定路径下所有文件名
        /// </summary>
        /// <param name="path">文件写入流</param>
        public static void getFileName(string path)
        {
            string filePath = string.Empty;
            string newFilePath = string.Empty;
            DirectoryInfo root = new DirectoryInfo(path);
            FileInfo[] files = root.GetFiles();
            foreach (FileInfo f in files)
            {
                filePath = f.FullName;  //完整的目录名 
                newFilePath = filePath.Replace("D:\\DataImgs", "D:\\DataImgs\\thumbnail");
                if (f.Name.ToLower().Contains("mp4") || f.Name.ToLower().Contains("avi") || f.Name.ToLower().Contains("rmvb"))
                {
                    //针对MP4,把第一帧存为图片
                    GetPicFromVideo(filePath, "100*160", "1", ffmpeg);
                }
                else
                {
                    //如果是图片都放到thumbnail文件夹下
                    GetPicThumbnail(filePath, newFilePath, 40);
                }
            }
        }
        #endregion

        #region 获取指定路径下所有子目录名
        /// <summary>
        /// 获得指定路径下所有子目录名
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <param name="indent">输出时的缩进量</param>
        public static void getDirectory(string path)
        {
            getFileName(path);
            string dirPath = string.Empty;
            string newDirPath = string.Empty;
            DirectoryInfo root = new DirectoryInfo(path);
            DirectoryInfo[] dirs = root.GetDirectories();
            foreach (DirectoryInfo d in dirs)
            {
                dirPath = d.FullName;
                if (dirPath == "D:\\DataImgs\\thumbnail")
                {
                    MessageBox.Show("操作完成!");
                }
                else
                {
                    newDirPath = dirPath.Replace("D:\\DataImgs", "D:\\DataImgs\\thumbnail");  //更换文件夹创建路径
                    if (!Directory.Exists(newDirPath))   //如果不存在,则创建此文件夹
                    {
                        Directory.CreateDirectory(newDirPath);
                    }
                    getDirectory(dirPath);
                }
            }
        }
        #endregion



有了这几个文件,批量压缩或者单独在上传时压缩又能游刃有余了