[英]How to save thumbnail image while maintaining the correct aspect ratio?
我正在使用ASP.net開發一個網站。 用戶可以在那里上傳圖像。 保存圖像時,我正在保存一個小版本(Thumbnail)圖像。 為此,我使用此代碼
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
上面的線可以很好地用於風景照片。 但是,如果我上傳人像照片,將無法保持其正確的還原效果。 那么,如何優化上述代碼以保存縮略圖,同時保持其原始寬高比呢?
您可以通過某種方式簡單地減少圖像的寬度和高度。 這是我使用系數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"));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.