简体   繁体   中英

Releasing Bitmap from system memory to delete it C#

I'm trying to compare two images and delete the second one if they are the same image. When my program goes to delete a file, it throws an error: The process cannot access the file "C:\\Temp\\Image.jpg" because it is being used by another process

It seems to be an issue with this method not closing the bitmap file, but I have yet to find out a way to release the bitmap from system memory in order to delete it

    public static bool ImageCompareString(Bitmap firstImage, Bitmap secondImage)
    {
        MemoryStream ms = new MemoryStream();
        firstImage.Save(ms, ImageFormat.Png);
        string firstBitmap = Convert.ToBase64String(ms.ToArray());
        ms.Position = 0;

        secondImage.Save(ms, ImageFormat.Png);
        string secondBitmap = Convert.ToBase64String(ms.ToArray());

        if (firstBitmap.Equals(secondBitmap))
        {
            ms.Close();
            return true;
        }
        else 
        {
            ms.Close();
            return false;
        }
    }

Dispose the bitmap object of second image before deleting the actual file. So something like 'secondImage.Dispose()'

I would reccommend to use try cach, and run dispose, to free the resources in finnaly section. This will dispose the object even if exception was thrown:

    public static bool ImageCompareString(Bitmap firstImage, Bitmap secondImage)
{
    try
    {
        MemoryStream ms = new MemoryStream();
        firstImage.Save(ms, ImageFormat.Png);
        string firstBitmap = Convert.ToBase64String(ms.ToArray());
        ms.Position = 0;

        secondImage.Save(ms, ImageFormat.Png);
        string secondBitmap = Convert.ToBase64String(ms.ToArray());

        if (firstBitmap.Equals(secondBitmap))
        {
            return true;
        }
        else 
        {           
            return false;
        }
    } 
    catch(Exception ex)
    {
        //log it, display or whatever
    } 
    finnaly 
    {
        ms.Close();
        ms.Dispose();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM