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

时间:2012-04-11 06:31:59

标签: c#-4.0 memory-leaks out-of-memory

要更改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();


        }

如果亮度改变了几次,则显示“Out of memory”异常。我试图使用“使用块”,但仍然是静脉。

有什么想法吗?

请看链接 http://www.codeproject.com/Articles/227016/Image-Processing-using-Matrices-in-Csharp 并建议在方法中是否可以进行任何类型的优化(旋转,亮度,裁剪和撤消)。

1 个答案:

答案 0 :(得分: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。您可以通过这种方式提高性能并降低内存成本。
  • 使用using个对象时,始终使用Graphics个阻止。
  • 当您确定不再需要.Dispose()对象时,请致电Bitmap
相关问题