2012-12-20 162 views
0

我已經將我的圖像存儲在SQL服務器中,而imageContent是一個字節數組(其中包含存儲在數據庫中的圖像數據)。我使用以下代碼從主圖像創建縮略圖,目前我爲縮略圖(40x40)設置了明確的寬度和高度,但這會損壞我的圖像寬高比,如何找到原始圖像的寬高比並縮小它我的原始寬高比是否保持不變?使數據庫圖像縮略圖,同時保持長寬比

  Stream str = new MemoryStream((Byte[])imageContent); 
     Bitmap loBMP = new Bitmap(str); 
     Bitmap bmpOut = new Bitmap(40, 40); 
     Graphics g = Graphics.FromImage(bmpOut); 
     g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
     g.FillRectangle(Brushes.White, 0, 0, 40, 40); 
     g.DrawImage(loBMP, 0, 0, 40, 40); 
     MemoryStream ms = new MemoryStream(); 
     bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png); 
     byte[] bmpBytes = ms.GetBuffer(); 
     bmpOut.Dispose(); 
     //end new 

     Response.ContentType = img_type; 
     Response.BinaryWrite(bmpBytes);//imageContent,bmpBytes 
+1

你讀電流的大小,使一些計算,並創建新的大小。 – Aristos

+0

我知道,但我怎樣才能讀取當前的大小?這是我的主要問題 –

+1

用於保存圖像(從您的代碼)的'loBMP',具有與您的圖像大小相同的'loBMP.Width'和'loBMP.Height'。 – Aristos

回答

2

也許這可以幫助你:

public static Bitmap CreateThumbnail(Bitmap source, int thumbWidth, int thumbHeight, bool maintainAspect) 
{ 
     if (source.Width < thumbWidth && source.Height < thumbHeight) return source; 

     Bitmap image = null; 
     try 
     { 
      int width = thumbWidth; 
      int height = thumbHeight; 

      if (maintainAspect) 
      { 
       if (source.Width > source.Height) 
       { 
        width = thumbWidth; 
        height = (int)(source.Height * ((decimal)thumbWidth/source.Width)); 
       } 
       else 
       { 
        height = thumbHeight; 
        width = (int)(source.Width * ((decimal)thumbHeight/source.Height)); 
       } 
      } 

      image = new Bitmap(width, height); 
      using (Graphics g = Graphics.FromImage(image)) 
      { 
       g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
       g.FillRectangle(Brushes.White, 0, 0, width, height); 
       g.DrawImage(source, 0, 0, width, height); 
      } 

      return image; 
     } 
     catch 
     { 
      image = null; 
     } 
     finally 
     { 
      if (image != null) 
      { 
       image.Dispose(); 
      } 
     } 

     return null; 
}