2011-05-17 42 views
1

所以我需要一些調整大小。幫助圖像大小調整方法gdi

我發現了兩種不同的方法。

一個看起來是這樣的:

public static Byte[] ResizeImageNew(System.Drawing.Image imageFile, int targetWidth, int targetHeight) { 
     using(imageFile){ 
      Size newSize = CalculateDimensions(imageFile.Size, targetWidth, targetHeight); 

      using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) { 
       newImage.SetResolution(imageFile.HorizontalResolution, imageFile.VerticalResolution); 
       using (Graphics canvas = Graphics.FromImage(newImage)) { 
        canvas.SmoothingMode = SmoothingMode.AntiAlias; 
        canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; 
        canvas.PixelOffsetMode = PixelOffsetMode.HighQuality; 
        canvas.DrawImage(imageFile, new Rectangle(new Point(0, 0), newSize)); 
        MemoryStream m = new MemoryStream(); 
        newImage.Save(m, ImageFormat.Jpeg); 
        return m.GetBuffer(); 
       } 
      } 
     } 
    } 

另:

public static System.Drawing.Image ResizeImage(System.Drawing.Image originalImage, int width, int maxHeight) { 
     originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); 
     originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); 

     int NewHeight = originalImage.Height * width/originalImage.Width; 
     if (NewHeight > maxHeight) { 
      // Resize with height instead 
      width = originalImage.Width * maxHeight/originalImage.Height; 
      NewHeight = maxHeight; 
     } 

     System.Drawing.Image newImage = originalImage.GetThumbnailImage(width, NewHeight, null, IntPtr.Zero); 

     return newImage; 
    } 

我基本上是 '借' 兩種方法,而只是改變的點點滴滴。

但是 - 使用第一個,每當我調整到一個小一點的圖片,文件的大小實際上是更大的,則原

而且大大提高了第二,而尺寸看起來很可怕:/(!?)

我當然傾向於僅僅用第一種方法改善圖像質量,如果可能的話,但我看不出來,從我的角度看,一切看起來都是「高質量」的?

回答

1

您可能需要設置JPEG壓縮級別。目前它可能會保存在一個非常高的質量水平,這可能不是你想要的。

這裏看到更多的信息:http://msdn.microsoft.com/en-us/library/bb882583.aspx

但是請注意,這只是降低了圖像的分辨率並不一定會減少文件大小。由於壓縮的工作原理,由於插值模式而變得模糊的較小分辨率的文件可能會比原始文件大得多,但是由於有損算法,JPEG可能不是一個大問題。不過,如果原始文件之前非常簡單(比如「平面」網頁或簡單的矢量圖形),並且在調整大小後模糊不清,它可以對PNG產生巨大影響。

1

不管文件大小的問題,我肯定會推薦使用第一種方法,而不是使用GetThumbnailImage

GetThumbnailImage實際上會從源圖像中提取嵌入的縮略圖(如果存在)。不幸的是,這意味着如果您不預期並考慮嵌入式縮略圖,則可能會從某些未知的原始文件大小和質量(與原始文件相比)中縮放。這也意味着一次運行(使用嵌入的縮略圖)會比另一次運行(沒有嵌入的縮略圖)獲得非常不同的質量結果。

我已經多次使用類似於您的第一種方法的東西,雖然我偶爾看到了您所看到的內容,但結果一直更好。