C# 等比压缩图片,返回固定大小并居中

来源:互联网 发布:db2和mysql 迁移 编辑:程序博客网 时间:2024/05/16 01:12

等比压缩图片,返回固定大小并居中,如果图片不是正方形,周围就是空白。

        /// <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;        }


0 0
原创粉丝点击