1

I'm writing a simple image resizing program. By dragging multiple files onto the .exe, it will go through and resize each file. It works up to a certain point where an OOM (out of memory) exception is being thrown. I've tried calling Dispose on the bitmap and setting it to Null, but neither seems to do anything.

Bitmap current_image;
for (int i = 0; i < imagesfilepath.Count; ++i)
        {
            // Load the image. 
            if ( current_image != Null )
            {
                current_image.Dispose();
                current_image = Null;
            }
            current_image = (Bitmap)Image.FromFile(imagesfilepath[i], true);

            // Resize it.
            // Save it.
        }

The exception is generally thrown after 1.5 GB has been used. I can get around this issue by limiting the amount of images a user can resize at one time, but shouldn't I be able to just allocate memory for 1 Bitmap, and reuse it every iteration?

3 Answers3

3

Image.FromFile() throws OutOfMemoryException when the file is not a valid image:

Exception Condition OutOfMemoryException
The file does not have a valid image format. -or- GDI+ does not support the pixel format of the file.

Yes, this makes no sense and is confusing, but it is what it is.

MSDN: Image.FromFile

Jim Counts
  • 12,535
  • 9
  • 45
  • 63
  • All the files are exactly the same. Each are 1.02 MB and I can resize 73 of them just fine, 74 or greater and I get this: An unhandled exception of type 'System.OutOfMemoryException' occurred in System.Drawing.dll Additional information: Out of memory. – user1203277 Feb 11 '12 at 03:13
  • 1
    Try catching the exception. If you are really out of memory, then catching it will have no effect--you're out of memory. If, on the other hand, you are experiencing a GDI+ error, your loop will continue. – Jim Counts Feb 11 '12 at 03:19
1

The out of memory is caused by memory segmentation, lack of a contiguous memory block of required size. you should rather use the same buffer to avoid it.

Alex E
  • 11
  • 1
1

As long as you dispose of the images you should not receive the OutOfMemoryException. Tested with the following snippet where disposing allowed the program to finish successfully while not disposing caused the exception.

var path = @"C:\Users\mdearing\Desktop\Untitled.bmp";
for (var i = 0; i < 1000; i++)
{
    var image = Bitmap.FromFile(path);
    //image.Dispose(); //commenting this line out causes the OOM Exception
}
Matt Dearing
  • 9,286
  • 1
  • 23
  • 25