Process memory keeps increasing when capturing screen

Viewed 30

I am very new to C# and i cant figure out how to properly dispose of the "something" which causes the memory increase.

Bitmap CaptureScreen(int width, int heigth, int sourceX, int sourceY)
    {
        var image = new Bitmap(width, heigth, PixelFormat.Format24bppRgb);
        var gfx = Graphics.FromImage(image);
        gfx.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, sourceX, sourceY, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
        return image; 
    }

private bool ScanImage(Bitmap AsourceImage, Bitmap Atemplate)
    {
        System.Drawing.Bitmap sourceImage = AsourceImage;
        System.Drawing.Bitmap template = Atemplate;
        // create template matching algorithm's instance

        // (set similarity threshold to 92.1%)
        ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.921f);
        // find all matchings with specified above similarity

        //Convert to suported pixel format
        template = AForge.Imaging.Image.Clone(template, PixelFormat.Format24bppRgb);

        TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template);
        // highlight found matchings

        BitmapData data = sourceImage.LockBits(
             new Rectangle(0, 0, sourceImage.Width, sourceImage.Height),
             ImageLockMode.ReadWrite, sourceImage.PixelFormat);
        foreach (TemplateMatch m in matchings)
        {
            //MessageBox.Show("Match");
            sourceImage.UnlockBits(data);
            return true;
        }
        sourceImage.UnlockBits(data);
        return false;
    }

and then ill call something like this:

bool match= ScanImage(CaptureScreen(100, 100, -915, -490), (Bitmap)Bitmap.FromFile(@"C:\Users\mabon\source\repos\image.png"));
        if (match)
        {
            //dosomething
        }
        else
        {
            //else
        }

I was trying to find out which is causing it and i think its in the CaptureScreen procedure when i call it it never disposes of the returned image. Whenever i call the procedure the memory just keeps increasing.

0 Answers
Related