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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With