out of memory Image.FromFile

Why is it that I'm getting an out of memory error? Thank you

if (File.Exists(photoURI))
{
    FileStream fs = new FileStream(photoURI, FileMode.Open, FileAccess.Read);
    Image img = Image.FromStream(fs);
    fs.Close();
}

In the Image.FromFile documentation, an OutOfMemoryException can be throw if:

The file does not have a valid image format.

-or-

GDI+ does not support the pixel format of the file.

Check your image format.

Also, if you want to close the stream right after loading the image, you must make a copy of the image. Take a look here. GDI+ must keep the stream open for the lifetime of the image.


First mistake:

if (File.Exists())

The file system is volatile, and so access to your file can change in between the line with your if condition and the line following. Not only that, but File.Exists() might return true, but your FileStream could still throw an exception if you lack security permissions on the file or if it is already locked.

Instead, the correct way to handle this is with a try/catch block. Devote your development time to the exception handler instead, because you have to write that code anyway.

Second mistake:

fs.Close();

This line must be inside a finally block, or you have the potential to leave open file handles lying around. I normally recommend a using block to ensure this kind of resource is properly disposed, but since you already need the try/catch, you can use code like this instead:

Image img = null;
FileStream fs = null;
try
{
    fs = new FileStream(photoURI, FileMode.Open, FileAccess.Read);    
    img = Image.FromStream(fs);    
}
finally
{
    fs.Close();
}

See this reply by Hans Passant:

GDI+ was written quite a while before .NET ever came around. The SDK wrapper for it was written in C++. To keep it compatible, it couldn't use exceptions. Error conditions were reported with error codes. That never scales well, GDI+ has only 20 error codes. That's not much for such a large chunk of code.

The Status::OutOfMemory error code got overloaded to mean different things. Sometimes it really does mean out of memory, it can't allocate enough space to store the bitmap bits. Sadly, don't know how that happened, an image file format problem is reported by the same error code. There is no dedicated error code that could more accurately describe it, I guess.