C# 生成縮圖

_shc發表於2019-02-19

個人覺得比較好用的縮圖方法,用在每次從FTP服務端下載圖片,之後引用該方法進行壓縮圖片;

/// <summary>
        /// 生成縮圖
        /// </summary>
        /// <param name="localImagePath">圖片地址</param>
        /// <param name="thumbnailImagePath">縮圖地址</param>
        /// <param name="width">圖片寬度</param>
        /// <param name="height">圖片高度</param>
        /// <param name="p"></param>
        public static void GetThumbnail(string localImagePath, string thumbnailImagePath, int width, int height)
        {
            System.Drawing.Image serverImage = System.Drawing.Image.FromFile(localImagePath);
            //畫板大小
            int towidth = width;
            int toheight = height;
            //縮圖矩形框的畫素點
            int x = 0;
            int y = 0;
            int ow = serverImage.Width;
            int oh = serverImage.Height;
 
            if (ow > oh)
            {
                toheight = serverImage.Height * width / serverImage.Width;
            }
            else
            {
                towidth = serverImage.Width * height / serverImage.Height;
            }
            //新建一個bmp圖片
            System.Drawing.Image bm = new System.Drawing.Bitmap(width, height);
            //新建一個畫板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);
            //設定高質量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //設定高質量,低速度呈現平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空畫布並以透明背景色填充
            g.Clear(System.Drawing.Color.White);
            //在指定位置並且按指定大小繪製原圖片的指定部分
            g.DrawImage(serverImage, new System.Drawing.Rectangle((width - towidth) / 2, (height - toheight) / 2, towidth, toheight),
                0, 0, ow, oh,
                System.Drawing.GraphicsUnit.Pixel);
            try
            {
                //以jpg格式儲存縮圖
                bm.Save(thumbnailImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                serverImage.Dispose();
                bm.Dispose();
                g.Dispose();
            }
        }

  轉載自:http://www.wxzzz.com/1413.html

相關文章