Wednesday, June 21, 2006

Image.FromFile gives "Out of Memory" exception

It took me a few minutes to find the solution to this so I thought I'd post it on the web for others to find.

If you use the System.Drawing.Image.FromFile method on a file that you do not have sufficient permission to, you will get a "Out of memory" exception. That's right, you would expect a security exception here but that's not the case.

I wish I could remember the forum where I saw this solution so I could give credit. In any case, create a FileStream object from your file and then use the FromStream method on the Image object. This will give you much more intelligent exceptions.


Ralph said...

Hi Joe, thanks a lot for putting this on your site! :-)

After googling for quite a while I found the solution for this stupid System.Drawing.Image.FromFile error here...

I was actually looking into the wrong direction for a while, because some posts mentioned that whenever the image object is not 96 dpi, it will result in a FromFile "Out of Memory" exception. My 96 dpi files were exactly the ones that didn't load, but apparently it was caused because they didn't have the correct access rights (it didn't allow read permissions from COMPUTERNAME\Users).


Unknown said...


Iam also facing the same problem. I want to load a tif image into picture box.

FileStream fs = File.OpenRead(imagepath);
Image img = Image.FromStream(fs);

But im facing the same prob like memory out of exception. Wat may be the reason.

Nice article.

Mickey said...

Interesting, I still get Memeory error whether I use stream or not. and all files have everyone full control.

Hato0be said...

I'm getting the same error. For first time was "Out of memory" when using

Image.FromFile(sFilePath, false);

but when when i used:

FileStream fs = new FileStream(sFilePath, FileMode.Open, FileAccess.Read);
Image img = Image.FromStream(fs, true, true);

I get "Parameter is not valid.".

Who knows what am i doing wrong?

Christopher Joseph Dean Schaefer said...

put a try catch block on the stream section and a different one on the image section that should give you a little better feedback as too the cause of the problem.

If it is giving you an invalid parameter maybe the stream isn't opening correctly. Try increasing the read and or write timeouts.

It could be that it isn't opening in time so it gives up so the image class gets a null stream.

ps. I found this on google and have no idea how old it is now.

mauricio said...

Thanks... I took care of this a while ago on one of my servers but totally forgot what was the cause. This helped remember exactly how to fix it.

Anonymous said...

make sure the file exists on the server.


Unknown said...

Also make sure that you do not have a zero byte file. We had some image files that were improperly transfered through FTP.

File.Exists() returned True, but Image.FromFile() still gave the "Out of Memory" exception.

PRAVINTH G said...

It helped me. thanks - Pravinth.G