2012-04-11 27 views
0

要更改c#.net 4中圖像的亮度,我使用了以下方法。亮度方法顯示「內存不足」異常

public void SetBrightness(int brightness) 
    { 
     imageHandler.RestorePrevious(); 
     if (brightness < -255) brightness = -255; 
     if (brightness > 255) brightness = 255; 
     ColorMatrix cMatrix = new ColorMatrix(CurrentColorMatrix.Array); 
     cMatrix.Matrix40 = cMatrix.Matrix41 = cMatrix.Matrix42 = brightness/255.0F; 
     imageHandler.ProcessBitmap(cMatrix); 
    } 

     internal void ProcessBitmap(ColorMatrix colorMatrix) 
      { 
      Bitmap bmap = new Bitmap(_currentBitmap.Width, _currentBitmap.Height) 

      ImageAttributes imgAttributes = new ImageAttributes(); 
      imgAttributes.SetColorMatrix(colorMatrix); 
      Graphics g = Graphics.FromImage(bmap); 
      g.InterpolationMode = InterpolationMode.NearestNeighbor; 
      g.DrawImage(_currentBitmap, new Rectangle(0, 0, _currentBitmap.Width, 
      _currentBitmap.Height), 0, 0, _currentBitmap.Width, 
      _currentBitmap.Height, GraphicsUnit.Pixel, imgAttributes); 
      _currentBitmap = (Bitmap)bmap.Clone(); 


     } 

如果亮度多次改變,則會顯示「內存不足」異常。我曾嘗試使用「使用塊」,但仍然堅持下去。

任何想法?

請參閱鏈接 http://www.codeproject.com/Articles/227016/Image-Processing-using-Matrices-in-Csharp 並建議在方法(旋轉,亮度,裁剪和撤消)中是否可以進行任何類型的優化。

+0

你可能忘記對位圖對象調用Dispose()。他們需要大量的非託管內存,垃圾收集器不會讓你擺脫麻煩。 – 2012-04-11 10:09:16

回答

0

我已經從CodeProject下載了項目,並修復了內存泄漏。在覆蓋它之前,您需要處理Graphics對象和_currentBitmap圖像。此外,您需要停止使用.Clone

如果您要更換與此代碼的ProcessBitmap函數的內容,內存泄漏消失:

internal void ProcessBitmap(ColorMatrix colorMatrix) 
{ 
    Bitmap bmap = new Bitmap(_currentBitmap.Width, _currentBitmap.Height); 
    ImageAttributes imgAttributes = new ImageAttributes(); 
    imgAttributes.SetColorMatrix(colorMatrix); 
    using (Graphics g = Graphics.FromImage(bmap)) 
    { 
     g.InterpolationMode = InterpolationMode.NearestNeighbor; 
     g.DrawImage(_currentBitmap, new Rectangle(0, 0, _currentBitmap.Width, _currentBitmap.Height), 0, 0, _currentBitmap.Width, _currentBitmap.Height, GraphicsUnit.Pixel, imgAttributes); 
    } 
    _currentBitmap.Dispose(); 
    _currentBitmap = bmap; 
} 

另外,這裏有一些提示,進一步優化:使用.Clone()

  • 停止。我已經看到了代碼,它在任何地方都使用.Clone()。除非真的必要,否則不要克隆對象。在圖像處理中,您需要大量內存來存儲大型圖像文件。你需要儘可能多地進行處理。
  • 您可以在方法之間傳遞Bitmap對象by reference。您可以通過這種方式提高性能並降低內存成本。
  • Graphics對象一起使用時,始終使用using塊。就當你確定了Bitmap對象
  • 呼叫.Dispose()你不需要他們了
+0

此外,您需要了解如何[接受答案(鏈接)](http://meta.stackexchange.com/a/5235)。如果您找到適合您的答案,請點擊旁邊的複選框。 – Ove 2012-04-16 06:43:21