等比例缩放图片

/// <summary>
/// 等比例缩放图片
/// </summary>
/// <param name="b">需要缩放的图片</param>
/// <param name="destHeight">缩放高度</param>
/// <param name="destWidth">缩放宽度</param>
/// <param name="color">画布背景色</param>
/// <returns></returns>
public static Bitmap GetThumbnail(Bitmap b, int destHeight, int destWidth,Color color)
{

System.Drawing.Image imgSource = b;

System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat;

int sW = 0, sH = 0;

// 按比例缩放

int sWidth = imgSource.Width;

int sHeight = imgSource.Height;

if (sHeight > destHeight || sWidth > destWidth)
{

if ((sWidth * destHeight) > (sHeight * destWidth))
{

sW = destWidth;

sH = (destWidth * sHeight) / sWidth;

}

else
{

sH = destHeight;

sW = (sWidth * destHeight) / sHeight;

}

}

else
{

sW = sWidth;

sH = sHeight;

}

Bitmap outBmp = new Bitmap(destWidth, destHeight);

Graphics g = Graphics.FromImage(outBmp);

g.Clear(color);

// 设置画布的描绘质量

g.CompositingQuality = CompositingQuality.HighQuality;

g.SmoothingMode = SmoothingMode.HighQuality;

g.InterpolationMode = InterpolationMode.HighQualityBicubic;

g.DrawImage(imgSource, new Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);

g.Dispose();

// 以下代码为保存图片时,设置压缩质量

using (MemoryStream ms = new MemoryStream())
{
EncoderParameters encoderParams = new EncoderParameters();
long[] quality = new long[1];
quality[0] = 100;
EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
encoderParams.Param[0] = encoderParam;
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}

outBmp.Save(ms, jpegICIinfo, encoderParams);
outBmp = (Bitmap)Bitmap.FromStream(ms);
}
imgSource.Dispose();

return outBmp;

}
#endregion

posted @ 2017-02-13 17:31  奋斗的大鹏  阅读(247)  评论(0)    收藏  举报