您的位置:首页 > 编程语言 > C#

按大小缩放图片

2016-01-17 21:18 429 查看
这是一段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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# 位图