2017-01-20 5 views
0

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

이미지의 너비와 높이를 어느 정도 줄일 수 있습니다. 다음은 요인 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")); 
    } 
} 
관련 문제