0

I am uploading a big image ~10Mb and I have the following code:

public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
    foreach (var file in files)
    {
        var image = Image.FromStream(file.InputStream, true, true);
        ...
    }
}

Sometime it throws Out of Memory, sometimes GDI+ generic errors. I cannot reproduce this in a console app with the following code:

using (FileStream stream = File.Open(@"d:\test.jpg", FileMode.Open))
{
    var image = Image.FromStream(stream);
}

What can be the cause for those exceptions? One note: for small images everything works great.

Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
  • Your web server has a limit on how much memory can use. (You can find how many if you are have access on the Advanced settings of the application pool). Now remember that the files on the web server are on a raw form. The Console app cannot reproduce that because it gets memory on demand. – Nick Polyderopoulos Jun 06 '17 at 23:06

2 Answers2

0

Refer- out of memory Image.FromFile

I think the reason you are not able to reproduce this in console app is because you are using disposable code block (using block).

Try changing you code to something like this-

public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
    foreach (var file in files)
    {
        fs = new FileStream(image_url, FileMode.Open, FileAccess.Read);    
        img = Image.FromStream(fs);  
        var image = Image.FromStream(fs);
        ...

        //after you are done call below line
        fs.Close();
    }
}

Or you can use using block within your for-loop-

public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
    foreach (var file in files)
    {
        using (FileStream stream = File.Open(<give_file_URL_here>, FileMode.Open))
        {
            var image = Image.FromStream(stream);
            //...
        }
    }
}
Souvik Ghosh
  • 4,456
  • 13
  • 56
  • 78
  • Actually there is only one image uploaded. I tried with using block and it still throws the same exceptions. By the way the image is uploaded and not opened from the disk. – Giorgi Nakeuri Jun 06 '17 at 19:20
0

I have read answers on many similar exceptions and none could be applied to my case. Image itself was not corrupted or with incorrect bits. The thing was that I was debugging in 32 bit mode. As soon as I change this setting in VS2015 it worked like a charm. Seems Image.FromStream requires a lot of RAM for big images.

Tools -> Options -> Projects and Solutions -> Web Projects -> Use the 64 bit...

Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75