我正在使用ASP.net开发一个网站 . 在那里用户可以上传图像 . 当我保存图像时,我保存了一个小版本(缩略图)图像 . 为此,我使用此代码
public void SaveThumbnailImage(Stream sourcePath, int width, int height, string imageFileName)
{
using (var image = System.Drawing.Image.FromStream(sourcePath))
{
//a holder for the result
Bitmap result = new Bitmap(width, height);
//set the resolutions the same to avoid cropping due to resolution differences
result.SetResolution(image.HorizontalResolution, image.VerticalResolution);
//use a graphics object to draw the resized image into the bitmap
using (Graphics graphics = Graphics.FromImage(result))
{
//set the resize quality modes to high quality
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
//draw the image into the target bitmap
graphics.DrawImage(image, 0, 0, result.Width, result.Height);
}
thumbnailfullImagePath = string.Format("/Images/thumbnail/{0}", imageFileName);
result.Save(Server.MapPath(thumbnailfullImagePath), image.RawFormat);
}
}
高度为:105宽度为150
以上电线适用于风景型照片 . 但如果我上传一张肖像照片,它就不能保持正确的分辨率 . 那么如何优化上面的代码来保存缩略图,同时保持其原始的宽高比?
1 回答
您可以通过某种因素简单地减小图像的宽度和高度 . 这是我使用因子10的示例代码 .