Search code examples
c#gdi

loading lots of images causes out of memory


I swear I knew the answer to this one but I forgot.

I have this function. It loads bitmaps and draws them. it can be called in rapid succession. After about 300 or so bitmaps the application crashes with a System.OutOfMemoryException.

Please tell me what am I doing wrong again :)

    private void PaintPicture()
    {
        string FullPath = Global.RunttimePath + EditType.FilePath;

        if (File.Exists(FullPath))
        {
            Image i = Image.FromFile(FullPath);
            //DrawImage(i, pnlPicture, pbColor.BackColor); //I disabled this so the problem is not here
            i.Dispose();
            //GC.Collect(); //I know I know... I should never call GC. So disabled it :) 
        }
        else
        {
            //DrawImage(Properties.Resources.Fail800, pnlPicture, Color.White, true);
        }
    }

Solution

  • According to the documentation of Image.FromFile you can get an OutOfMemoryException if the bitmap is in an unknown format. Make sure your application can safely load all images you're trying to use and see if it always crashes on the same image.

    If it's always the same image then you can try re-saving the image in a supported pixel format (using Photoshop or Paint.Net or some other free tool) - this should fix the particular image that breaks your application.

    Also, add an exception handler around your drawing logic to make sure your application doesn't crash when it runs into a bad image - GDI+ only supports a relatively low number of image formats.

    To verify if you're actually running out of memory (that is, if there is a leak), monitor memory use while your application is running. If you see signs of a memory leak, your problem is likely elsewhere.

    Edit:

    Read these questions / answers for advice about using Image.FromStream instead of FromFile() - doing so avoids locking the file for a long time:

    File.Delete failing when Image.FromFile was called prior it, despite making copy of loaded image and destroying original one

    out of memory Image.FromFile