按大小缩放图片

这是一段c#代码,根据指定长宽把图片按原比例进行缩放,产生的空白部分可指定颜色。

public static Bitmap ShrinkImage(Bitmap img, int width, int height, Color bgColor)
        {
            Bitmap ret = null;
            if (img.Width == 0 || img.Height == 0)
            {
                ret = new Bitmap(0, 0);
                return ret;
            }
            // calc the smaller ratio
            double w = (double)width / img.Width;
            double h = (double)height / img.Height;
            double r = w > h ? h : w;
            ret = new Bitmap(width, height);
            Bitmap img2 = null;
            if (w > 1.0 && h > 1.0)
            {
                // pic smaller than rect
                img2 = img;
            }
            else
            {
                // one side is bigger that rect
                img2 = new Bitmap(img.GetThumbnailImage((int)(img.Width*r), (int)(img.Height*r), null, new IntPtr()));
            }
            int x = (width - img2.Width) / 2;
            int y = (height - img2.Height) / 2;
            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    if ((i >= x && i < (img2.Width+x)) &&
                        (j >= y && j < (img2.Height+y)))
                    {
                        ret.SetPixel(i, j, img2.GetPixel(i - x, j - y));
                    }
                    else
                    {
                        ret.SetPixel(i, j, bgColor);
                    }
                }
            }
            return ret;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值