Reputation: 33
I have written some c# code that needs to process upwards of about 3000 images, but by the 500th image the task manager is showing the program using 1.5gb of memory. The function below seems to be one of the major culprits. What could I be doing better here? Any help or suggestions are appreciated. Thanks.
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
}
Upvotes: 3
Views: 1131
Reputation: 10940
i could reduce memory when changing your code like this
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;
}
so it seems to be a good idea, to free up that image memory right away, and not to wait until the GC takes care of it eventually.
Upvotes: 1