/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="maxWidth">生成的缩略图最大宽度</param>
/// <param name="maxHeight">生成的缩略图最大高度</param>
/// <param name="imgFileStream">图片文件流对象</param>
/// <param name="savePath">文件保存路径</param>
/// <param name="imgFormat">生成图片的格式</param>
public void GenerateThumbnail(int maxWidth, int maxHeight, System.IO.Stream imgFileStream, string savePath,
System.Drawing.Imaging.ImageFormat imgFormat)
{
using (var img = System.Drawing.Image.FromStream(imgFileStream))
{
var sourceWidth = img.Width;
var sourceHeight = img.Height;
var thumbWidth = sourceWidth; //要生成的缩略图的宽度
var thumbHeight = sourceHeight; //要生成的缩略图的高度
//计算生成图片的高度和宽度
if (sourceWidth > maxWidth || sourceHeight > maxHeight)
{
var rateWidth = (double)sourceWidth / maxWidth;
var rateHeight = (double)sourceHeight / maxHeight;
if (rateWidth > rateHeight)
{
thumbWidth = maxWidth;
thumbHeight = (int)Math.Round(sourceHeight / rateWidth);
}
else
{
thumbWidth = (int)Math.Round(sourceWidth / rateHeight);
thumbHeight = maxHeight;
}
}
using (var bmp = new System.Drawing.Bitmap(thumbWidth, thumbHeight))
{
//从Bitmap创建一个System.Drawing.Graphics对象,用来绘制高质量的缩小图。
using (var gr = System.Drawing.Graphics.FromImage(bmp))
{
//设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//下面这个也设成高质量
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//下面这个设成High
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//把原始图像绘制成上面所设置宽高的缩小图
var rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
gr.DrawImage(img, rectDestination, 0, 0, sourceWidth, sourceHeight,
System.Drawing.GraphicsUnit.Pixel);
//保存图像
bmp.Save(savePath, imgFormat);
}
}
}
}
调用很简单如下
protected void Button4_Click(object sender, EventArgs e)
{
GenerateThumbnail(500, 500, FileUpload1.PostedFile.InputStream, "d:/1.jpg",
System.Drawing.Imaging.ImageFormat.Jpeg);
}