1. 程式人生 > >C# 等比壓縮圖片,返回固定大小並居中

C# 等比壓縮圖片,返回固定大小並居中

等比壓縮圖片,返回固定大小並居中,如果圖片不是正方形,周圍就是空白。

        /// <summary>
        /// 等比壓縮圖片,返回固定大小並居中
        /// </summary>
        /// <param name="mg"></param>
        /// <param name="newSize"></param>
        /// <returns></returns>
        public static Bitmap ResizeImage(Bitmap mg, Size newSize)
        {
            double ratio;//壓縮比
            int myWidth;
            int myHeight;
            int x = 0;
            int y = 0;
            if ((mg.Width / Convert.ToDouble(newSize.Width)) > (mg.Height / Convert.ToDouble(newSize.Height)))
                ratio = Convert.ToDouble(mg.Width) / Convert.ToDouble(newSize.Width);
            else
                ratio = Convert.ToDouble(mg.Height) / Convert.ToDouble(newSize.Height);
            myHeight = (int)Math.Ceiling(mg.Height / ratio);
            myWidth = (int)Math.Ceiling(mg.Width / ratio);
            Bitmap bp = new Bitmap(newSize.Width, newSize.Height);
            x = (newSize.Width - myWidth) / 2;
            y = (newSize.Height - myHeight) / 2;
            System.Drawing.Graphics g = Graphics.FromImage(bp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            Rectangle rect = new Rectangle(x, y, myWidth, myHeight);
            g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pixel);
            return bp;
        }