Image.FromFile Throws OutOfMemoryException

Let's say you are writing a WinForms app and you need to create an Image object (from the System.Drawing namespace), and on that Image object you need to load the actual image at runtime, like for an icon or bitmap. There is a static method on the Image class named FromFile, which is used to create an Image from the given file. So all you need to do is pass in a .bmp, .jpg, .ico, .gif, etc and you're good to go.

However, there is one issue that could potentially throw someone for a loop: if the file you gave the Image.FromFile method is not a valid image format, you get an OutOfMemoryException. You'd think the more smarter* thing to do would be to throw a InvalidImageFormatException or something similar. But no, you get an OutOfMemoryException, which is very misleading and could lead someone down the wrong path if they are troubleshooting the problem. So be sure that when using Image.FromFile you put it in a try...catch block and catch an OutOfMemoryException (and a FileNotFoundException as well).

* = an inside joke between myself, Drew, and Brian Prince. Drew actually said in a presentation, “...someone more smarter than me...”, and Brian and I have never let him live that down. So if you see or hear one of us say “more smarter”, that's where it came from.

Print | posted on Wednesday, March 30, 2005 7:53 AM

Feedback

# re: Image.FromFile Throws OutOfMemoryException

left by Jennifer at 3/30/2005 12:12 PM
That pacific statement is funny.

# re: Image.FromFile Throws OutOfMemoryException

left by Jon Sims at 7/20/2005 7:10 AM
Hi Dave,

You mention the FileNotFoundException in passing above - any idea why I might be getting that? I am trying to convert an image file from a tif to a gif and I keep getting that error. The path is correct and the file is there...

Regards, Jon Sims (jon.sims@avonandsomerset.police.uk

# re: Image.FromFile Throws OutOfMemoryException

left by Jon Sims at 7/20/2005 7:10 AM
Hi Dave,

You mention the FileNotFoundException in passing above - any idea why I might be getting that? I am trying to convert an image file from a tif to a gif and I keep getting that error. The path is correct and the file is there...

Regards, Jon Sims (jon.sims@avonandsomerset.police.uk)

# re: Image.FromFile Throws OutOfMemoryException

left by Griffin at 10/24/2005 2:08 AM
I noticed that whenever you use Image.FromFile, the Pagefile Usage just keeps on incrementing. Do you by chance know how I can free the resources after the image has already been loaded?

Thanks,
Grif
Comments have been closed on this topic.