C# 4.0 亮度法显示;“内存不足”;例外
为了改变c#.NET4中图像的亮度,我使用了以下方法C# 4.0 亮度法显示;“内存不足”;例外,c#-4.0,memory-leaks,out-of-memory,C# 4.0,Memory Leaks,Out Of Memory,为了改变c#.NET4中图像的亮度,我使用了以下方法 public void SetBrightness(int brightness) { imageHandler.RestorePrevious(); if (brightness < -255) brightness = -255; if (brightness > 255) brightness = 255; ColorMatrix cMatrix =
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();
}
public亮度(整数亮度)
{
imageHandler.RestorePrevious();
如果(亮度<-255)亮度=-255;
如果(亮度>255)亮度=255;
ColorMatrix cMatrix=新的ColorMatrix(CurrentColorMatrix.Array);
cMatrix.Matrix40=cMatrix.Matrix41=cMatrix.Matrix42=亮度/255.0F;
ProcessBitmap(cMatrix);
}
内部空白处理位图(ColorMatrix ColorMatrix)
{
位图bmap=新位图(_currentBitmap.Width,_currentBitmap.Height)
ImageAttributes imgatAttributes=新的ImageAttributes();
imgAttributes.SetColorMatrix(colorMatrix);
Graphics g=Graphics.FromImage(bmap);
g、 插值模式=插值模式。最近的邻居;
g、 DrawImage(_currentBitmap,新矩形(0,0,_currentBitmap.Width,
_currentBitmap.Height),0,0,_currentBitmap.Width,
_currentBitmap.Height、GraphicsUnit.Pixel、imgAttributes);
_currentBitmap=(位图)bmap.Clone();
}
如果亮度多次改变,则显示“内存不足”异常。我曾尝试过使用“Using block”,但使用了静脉
有什么想法吗
请查看链接
并建议是否可以在方法中进行任何类型的优化(旋转、亮度、裁剪和撤消)。我已从CodeProject下载了项目,并修复了内存泄漏。您需要先处理图形对象和
\u 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
- 使用
对象时,始终使用图形
块使用
- 当您确定不再需要对象时,在
对象上调用位图
.Dispose()