Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aforge Memory Usage

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
    }
like image 611
DistroDrake Avatar asked Sep 19 '26 02:09

DistroDrake


1 Answers

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.

like image 185
esskar Avatar answered Sep 21 '26 15:09

esskar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!