2012-10-02 61 views
1

我有重新調整的位映射功能。這是我簡單地從另一個項目複製它這樣的「麪包和黃油」操作:如何調試誤導性的GDI OutOfMemory異常?

private Bitmap ResizeBitmap(Bitmap orig) 
{ 
    Bitmap resized = new Bitmap(this.Xsize, this.Ysize, PixelFormat.Format16bppGrayScale); 
    resized.SetResolution(orig.HorizontalResolution, orig.VerticalResolution); 
    using (Graphics g = Graphics.FromImage(resized)) 
    { 
     g.DrawImage(orig, 0, 0, resized.Width, resized.Height); 
    } 
    return resized; 
} 

不過,我一直在Graphics g = Graphics.FromImage(resized)越來越OutOfMemory異常。

我知道,when it comes to GDI, OutOfMemory exceptions usually mask other problems。我也很清楚,我想調整圖片的大小並不大而且(據我所知),因爲它們離開當前範圍GC應該沒有問題收集的情況。

不管怎樣,我一直在玩弄它一下,它目前看起來是這樣的:

private Bitmap ResizeBitmap(Bitmap orig) 
{ 
    lock(orig) 
    { 
     using (Bitmap resized = new Bitmap(this.Xsize, this.Ysize, PixelFormat.Format16bppGrayScale)) 
     { 
      resized.SetResolution(orig.HorizontalResolution, orig.VerticalResolution); 
      using (Graphics g = Graphics.FromImage(resized)) 
      { 
       g.DrawImage(orig, 0, 0, resized.Width, resized.Height); 
      } 
      return resized; 
     } 
    } 
} 

但現在我對resized.SetResolution(orig.HorizontalResolution, orig.VerticalResolution);

我得到InvalidOperation異常在黑暗中徘徊。有沒有更好的方法來解決這些煩人的GDI操作?

+0

只是想知道 - 你試圖使用GDI +在ASP.NET應用程序?我們這樣做了一段時間,直到我們發現它不被支持並且會崩潰(有時)。 – GarethOwen

+0

@GarethOwen不,這是一個winforms應用程序。 –

回答

2

Graphics.FromImage方法定義:

如果圖像具有索引像素格式,此方法將引發與所述消息的異常,「A圖形對象不能從具有索引像素格式的圖像創建的。 「

雖然你得到的例外是真的令人誤解,你正試圖執行不受支持的操作。它看起來像你需要調整這個位圖的原始內存塊,而不是GDI +位圖。

+0

只是檢查 - 'Format16bppGrayScale'被認爲是一個索引的像素格式? –

+0

是的,所有灰度圖像實際上索引格式,灰度調色板(0,0,0),(1,1,1)... Format16bppGrayScale被提及作爲在Graphics.FromImage MSDN主題不支持。 –

+0

謝謝。這解決了眼前的問題,但是我想讓問題保持開放一段時間,因爲我希望瞭解一般的調試技術。 –