views:

90

answers:

2

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();
}
+1  A: 

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();
}
Joel Coehoorn
You cannot close the stream if you want to use the image past this point. Take a look [here](http://stackoverflow.com/questions/3661799/file-delete-failing-when-image-fromfile-was-called-prior-it-despite-making-copy/3661892#3661892).
Jordão
In that case, I'd be inclined to wrap this in a class with it's own IDisposable implementation that behaves more intuitively.
Joel Coehoorn
+6  A: 

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.

Jordão
its a .png file format
xscape
Then, it's the pixel format.
Jordão
Try to open the image in another application, and save it with a different pixel format.
Jordão