.Net 圖片縮圖上傳通用方法

lin山發表於2018-07-31

日常開發中,經常碰到圖片上傳的需求,尤其在商城系統開發的時候,商品列表商品圖片展示如果使用高清原圖,由於高清原圖比較大,載入原圖時間會大大增加,直接導致系統效能底下,使用者體驗不好,併發量高的時候直接就掛掉了,這時候後臺上傳圖片的時候,就必須將原高清圖進行壓縮,生成高質量縮圖,然後在商品列表讀取縮圖可以大大減少載入時間,起到一個效能優化的作用,當然在商品詳情的時候還是得用高清原圖!

以下程式碼,可以在實際開發中使用將圖片高質量壓縮,話不多說,程式碼貼下:

 

         /// <summary>
        /// 生成縮圖或質量壓縮
        /// </summary>
        /// <param name="sourcePath">源圖路徑(物理路徑)</param>
        /// <param name="targetPath">縮圖路徑(物理路徑)</param>
        /// <param name="width">縮圖寬度,如果寬度為0則不縮略</param>
        /// <param name="height">縮圖高度,如果高度為0則不縮略</param>
        /// <param name="mode">生成縮圖的方式,預設為空,為空則不縮略高寬[HW 指定高寬縮放(不變形);W 指定寬,高按比例;H 指定高,寬按比例;CUT 指定高寬裁減(不變形)]</param>  
        /// <param name="flag">壓縮質量(數字越小壓縮率越高)1-100</param>
        /// <param name="size">壓縮後圖片的最大大小,0為不限制大小</param>
        public static void MakeThumbnail(string sourcePath, string targetPath, int width = 0, int height = 0, string mode = "", int flag = 100, int size = 0)
        {
            Image sourceImage = null;
            Image bitmap = null;
            Graphics g = null;
            EncoderParameters ep = null;
            EncoderParameter eParam = null;
            try
            {
                sourceImage = Image.FromFile(sourcePath);

                int toWidth = 0;
                if (width > 0)
                {
                    toWidth = width;
                }
                else
                {
                    toWidth = sourceImage.Width;
                }

                int toHeight = 0;
                if (height > 0)
                {
                    toHeight = height;
                }
                else
                {
                    toHeight = sourceImage.Height;
                }

                int x = 0;
                int y = 0;
                int ow = sourceImage.Width;
                int oh = sourceImage.Height;

                if (width > 0 && height > 0 && !string.IsNullOrWhiteSpace(mode))
                {
                    switch (mode.ToUpper())
                    {
                        case "HW"://指定高寬縮放(不變形)
                            int tempheight = sourceImage.Height * width / sourceImage.Width;
                            if (tempheight > height)
                            {
                                toWidth = sourceImage.Width * height / sourceImage.Height;
                            }
                            else
                            {
                                toHeight = sourceImage.Height * width / sourceImage.Width;
                            }
                            break;
                        case "W"://指定寬,高按比例                    
                            toHeight = sourceImage.Height * width / sourceImage.Width;
                            break;
                        case "H"://指定高,寬按比例
                            toWidth = sourceImage.Width * height / sourceImage.Height;
                            break;
                        case "CUT"://指定高寬裁減(不變形)                
                            if ((double)sourceImage.Width / (double)sourceImage.Height > (double)toWidth / (double)toHeight)
                            {
                                oh = sourceImage.Height;
                                ow = sourceImage.Height * toWidth / toHeight;
                                y = 0;
                                x = (sourceImage.Width - ow) / 2;
                            }
                            else
                            {
                                ow = sourceImage.Width;
                                oh = sourceImage.Width * height / toWidth;
                                x = 0;
                                y = (sourceImage.Height - oh) / 2;
                            }
                            break;
                    }
                }

                //新建一個bmp圖片
                bitmap = new Bitmap(toWidth, toHeight);

                //新建一個畫板
                g = Graphics.FromImage(bitmap);

                g.CompositingQuality = CompositingQuality.HighQuality;

                //設定高質量插值法
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                //設定高質量,低速度呈現平滑程度
                g.SmoothingMode = SmoothingMode.HighQuality;

                //清空畫布並以透明背景色填充
                g.Clear(Color.Transparent);

                //在指定位置並且按指定大小繪製原圖片的指定部分
                g.DrawImage(sourceImage, new Rectangle(0, 0, toWidth, toHeight),
                    new Rectangle(x, y, ow, oh),
                    GraphicsUnit.Pixel);

                //以下程式碼為儲存圖片時,設定壓縮質量
                ep = new EncoderParameters();
                long[] qy = new long[1];
                qy[0] = flag;//設定壓縮的比例1-100
                eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
                ep.Param[0] = eParam;

                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();//獲取影像編碼器的資訊
                ImageCodecInfo jpegICIinfo = null;
                for (int i = 0; i < arrayICI.Length; i++)
                {
                    if (arrayICI[i].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[i];
                        break;
                    }
                }

                if (jpegICIinfo != null)
                {
                    bitmap.Save(targetPath, jpegICIinfo, ep);
                    FileInfo fiTarget = new FileInfo(targetPath);
                    if (size > 0 && fiTarget.Length > 1024 * size)
                    {
                        flag = flag - 10;
                        MakeThumbnail(sourcePath, targetPath, width, height, mode, flag, size);
                    }
                }
                else
                {
                    //以jpg格式儲存縮圖
                    bitmap.Save(targetPath, ImageFormat.Jpeg);
                }


            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sourceImage != null)
                {
                    sourceImage.Dispose();
                }
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (g != null)
                {
                    g.Dispose();
                }
                if (ep != null)
                {
                    ep.Dispose();
                }
                if (eParam != null)
                {
                    eParam.Dispose();
                }
            }
        }

 

相關文章