亮度方法显示“内存不足”异常

问题描述:

要更改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

我已经从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