我正在使用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
以上线缆适用于风景照片。但如果我上传一张肖像照片,它就不能保持正确的分辨率。那么如何优化上面的代码来保存缩略图,同时保持其原始的宽高比?
答案 0 :(得分:0)
您可以通过某种因素简单地减小图像的宽度和高度。这是我使用因子10的示例代码。
using System;
using System.Drawing;
public partial class thumbnail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath("images/send.png"));
int factor = 10;
int new_width = image.Width / factor;
int new_height = image.Height / factor;
System.Drawing.Image thumbnail = image.GetThumbnailImage(new_width,
new_height, null, IntPtr.Zero);
thumbnail.Save(Server.MapPath("images/send_thumbnail.png"));
}
}