C# 调整图像大小

public static System.Drawing.Image ResizeImage(System.Drawing.Image img, Size size)
{
//获取图片宽度
int sourceWidth = img.Width;
//获取图片高度
int sourceHeight = img.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
//计算宽度的缩放比例
nPercentW = ((float)size.Width / (float)sourceWidth);
//计算高度的缩放比例
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
//期望的宽度
int destWidth = (int)(sourceWidth * nPercent);
//期望的高度
int destHeight = (int)(sourceHeight * nPercent);

Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//绘制图像
g.DrawImage(img, 0, 0, destWidth, destHeight);
g.Dispose();
return (System.Drawing.Image)b;
}

posted @ 2022-05-16 17:37  淮雨清青  阅读(500)  评论(0)    收藏  举报