out of memory Image.FromFile

53,397

Solution 1

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.

Solution 2

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();
}

Solution 3

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.

Solution 4

I had the same problem, out of memory exception for an image or a bitmap and i tried resizing, painting it on panels and picture boxes, the lot. I had the memory available, so the exception was a bit of a red herring in my case.

After hours of kicking the PC I found that it was a third-party DLL that was not closing a stream. Some 'writeline' debugging that may be useful to check whether you do actually have the memory available:

proc = Process.GetCurrentProcess();
Console.WriteLine("Memory Usage" + proc.PrivateMemorySize64);

Solution 5

You can't use Image.FromStream for your file, instead you must decode the file using TiffBitmapDecoder. Sample code from MSDN:

// Open a Stream and decode a TIFF image
Stream imageStreamSource = new FileStream("tulipfarm.tif", FileMode.Open, FileAccess.Read, FileShare.Read);
TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];

// Draw the Image
Image myImage = new Image();
myImage.Source = bitmapSource;
myImage.Stretch = Stretch.None;
myImage.Margin = new Thickness(20);
Share:
53,397
xscape
Author by

xscape

simple and straight forward

Updated on October 18, 2020

Comments

  • xscape
    xscape over 3 years

    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();
    }
    
  • Jordão
    Jordão over 13 years
    You cannot close the stream if you want to use the image past this point. Take a look here.
  • Joel Coehoorn
    Joel Coehoorn over 13 years
    In that case, I'd be inclined to wrap this in a class with it's own IDisposable implementation that behaves more intuitively.
  • Jordão
    Jordão over 13 years
    Try to open the image in another application, and save it with a different pixel format.
  • hello_earth
    hello_earth over 9 years
    but check the answers at the bottom of this thread - apparently the above exception is also thrown when the handle to the image file is open and kept by some other process (e.g. System) - especially when the exception is thrown "out of the blue" in a code that used to work
  • hello_earth
    hello_earth over 9 years
    that definitely gave me a hint to check the files, opening which was causing the problem - using Find Handle/DLL in Process Explorer showed that they had open handles kept by the System process - i had to close the handles manually (ok, i absolutely didn't know what was keeping them - if i knew i would definitely close them normally) and the problem vanished
  • Trevi Awater
    Trevi Awater over 8 years
    fs?.Close() for c# 6 and above.
  • Sebastian Mach
    Sebastian Mach almost 6 years
    Are you sure this is an answer to this question?