Search code examples
c#iodelete-fileaforgeimaging

AForge.Imaging ProcessImage() method doesn't release the image file


I need to take a print screen of an active window and find out if it contains a particular sub-image in it. To check if screenshot (largeImage) contains smallImage I use AForge library (from NuGet) / ProcessImage() method. After comparing images I need to delete the screenshot (largeImage), however I get an exception saying:

The process cannot access the file 'c:\largeImage' because it is being used by another process.

After some debugging I can see that it is the FindSubImage() method that is locking the file.

FindSubImage() is implemented like this:

private bool FindSubImage(string largeImagePath, string smallImagePath)
{
    Bitmap largeImage = (Bitmap)Bitmap.FromFile(largeImagePath);
    Bitmap smallImage = (Bitmap)Bitmap.FromFile(smallImagePath);

    ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.8f);

    TemplateMatch[] match = tm.ProcessImage(largeImage, smallImage);
    if (match.Length > 0)
    {
        return true;
    }
    return false;
}

largeImage is ofcourse the screenshot I just took.

I tried wrapping the code with using(){} but it gives me an error saying:

type used in a using statement must be implicitly convertible to 'System.IDisposable'

Any idea how to delete the largeImage after use?


Solution

  • After playing a little more I managed to find two solutions:

    Solution1:

    I had to dispose of the Bitmap object before returning:

    largeImage.Dispose();    
    if (match.Length > 0)
    {
        return true;
    }
    return false;
    

    Solution 2:

    As per AForge documentation, you should use AForge methods for loading picture from file, which resolves the .NET problem with locking the file. So I replaced my code, where I load bitmap from file with this:

    //Bitmap mainImage = (Bitmap)Bitmap.FromFile(mainImagePath);
    //Bitmap subImage = (Bitmap)Bitmap.FromFile(subImagePath);
    Bitmap mainImage = AForge.Imaging.Image.FromFile(mainImagePath);
    Bitmap subImage = AForge.Imaging.Image.FromFile(subImagePath);
    

    I tested both solutions on my code separately and both work.