2011-12-18 49 views
0

我無法明白爲什麼此代碼會創建之前1280x800的圖像的縮略圖,尺寸爲241kb至600x375,大小爲556kb。下面是代碼:C# - 在創建相同圖像的較小分辨率後圖像尺寸增加

using (System.Drawing.Image img = System.Drawing.Image.FromFile(@"c:\images\myImg.jpg")) 
{ 
    int sourceWidth = img.Width; 
    int sourceHeight = img.Height; 
    int thumbHeight, thumbWidth = 0; 
    decimal ratio = decimal.Divide(sourceHeight, sourceWidth); 
    if (sourceHeight > 600 || sourceWidth > 800) 
    { 
     if (ratio >= 1) // Image is higher than it is wide. 
     { 
      thumbHeight = 800; 
      thumbWidth = Convert.ToInt32(decimal.Divide(sourceWidth, sourceHeight) * thumbHeight); 
     } 
     else // Image is wider than it is high. 
     { 
      thumbWidth = 600; 
      thumbHeight = Convert.ToInt32(decimal.Divide(sourceHeight, sourceWidth) * thumbWidth); 
     } 

     using (Bitmap bMap = new Bitmap(thumbWidth, thumbHeight)) 
     { 
      Graphics gr = Graphics.FromImage(bMap); 

      gr.SmoothingMode = SmoothingMode.HighQuality; 
      gr.CompositingQuality = CompositingQuality.HighQuality; 
      gr.InterpolationMode = InterpolationMode.High; 

      Rectangle rectDestination = new Rectangle(0, 0, thumbWidth, thumbHeight); 

      gr.DrawImage(img, rectDestination, 0, 0, sourceWidth, sourceHeight, GraphicsUnit.Pixel); 

      bMap.Save(HttpContext.Current.Server.MapPath("~/i/" + filename + "_" + fileExtension)); 
     } 
    } 
} 

任何幫助將不勝感激。 謝謝, 本

+0

更改*尺寸*與改變圖像的*分辨率*不同。 您所做的只是縮小圖像尺寸,導致更多的像素被打包到更小的空間中。 – 2011-12-18 06:15:16

+0

很可能,輸入圖像的壓縮質量較低,而輸出圖像的壓縮質量較高。 – Rotem 2011-12-18 06:29:12

回答

3

您正在保存的圖像,使用jpeg壓縮壓縮作爲一個位圖圖像沒有壓縮。該問題的行是在這裏:

bMap.Save(HttpContext.Current.Server 
        .MapPath("~/i/" + filename + "_" + fileExtension)); 

僅僅因爲你有一個不同的文件擴展名保存它不會使生成的圖像文件的JPEG圖像。您需要使用Bitmap.Save overloads之一來指定要保存爲的圖像的格式。例如,

//Creating a second variable just for readability sake. 
var resizedFilePath = HttpContext.Current.Server 
      .MapPath("~/i/" + filename + "_" + fileExtension); 
bMap.Save(resizedFilePath, ImageFormat.Jpeg); 

當然,您正在依靠Microsoft的壓縮算法實現。這並不壞,但可能會有更好的。

現在,您可以做的是使用原始圖像的Image.RawFormat屬性來確定在Save方法中使用的壓縮類型。我有不同的成功檢索適當的方法,所以我通常使用ImageFormat.Png作爲備份(Png格式支持圖像透明度,Jpeg不)。