我编写了一些需要处理大约3000张图像的c#代码,但是在第500张图像中,任务管理器正在使用1.5gb的内存显示该程序。以下功能似乎是主要的罪魁祸首之一。我能在这里做得更好吗?任何帮助或建议表示赞赏。感谢。
private void FixImage(ref Bitmap field)
{
//rotate 45 degrees
RotateBilinear rot = new RotateBilinear(45);
field = rot.Apply(field); //Memory spikes 2mb here
//crop out unwanted image space
Crop crop = new Crop(new Rectangle(cropStartX, cropStartY, finalWidth, finalHeight));
field = crop.Apply(field); //Memory spikes 2mb here
//correct background
for (int i = 0; i < field.Width; i++)
{
for (int j = 0; j < field.Height; j++)
{
if (field.GetPixel(i, j).ToArgb() == Color.Black.ToArgb())
field.SetPixel(i, j, Color.White);
}
} //Memory usuage increases 0.5mb by the end
}
答案 0 :(得分:1)
我可以像这样更改代码时减少内存
private void FixImage(ref Bitmap field)
{
//rotate 45 degrees
RotateBilinear rot = new RotateBilinear(45);
var rotField = rot.Apply(field); //Memory spikes 2mb here
field.Dispose();
//crop out unwanted image space
Crop crop = new Crop(new Rectangle(cropStartX, cropStartY, finalWidth, finalHeight));
var cropField = crop.Apply(rotField); //Memory spikes 2mb here
rotField.Dispose();
//correct background
for (int i = 0; i < cropField.Width; i++)
{
for (int j = 0; j < cropField.Height; j++)
{
if (cropField.GetPixel(i, j).ToArgb() == Color.Black.ToArgb())
cropField.SetPixel(i, j, Color.White);
}
} //Memory usuage increases 0.5mb by the end
field = cropField;
}
因此,立即释放图像内存似乎是一个好主意,而不是等到GC最终处理它。