Search code examples
c#.netout-of-memorysystem.drawing

System.Drawing.Image.FromFile "System.OutOfMemoryException: Out of memory."


I get these errors every once in a while and I am not sure why. This code executes thousands of times a day and Ill get these errors every once in a while. One of the images is 94.9 KB, 1024x1024 image. The image is being read from an Azure File Storage disk via UNC Path.

System.OutOfMemoryException: Out of memory.

Generated: Sat, 23 Apr 2016 15:09:54 GMT

System.OutOfMemoryException: Out of memory.
   at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
   at System.Drawing.Image.FromFile(String filename)
   at Tournaments.ImageHandler.ProcessRequest(HttpContext context) in C:\Development\Exposure\Main\Websites\Tournaments\ImageHandler.ashx.cs:line 64
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Actual Code

 using (var image = Image.FromFile(path))
 {
 }

Solution

  • This seemed to fix my issue as it doesn't hold a reference to it this way.

    using (var memoryStream = new MemoryStream(File.ReadAllBytes(path)))
                {
                    using (var image = Image.FromStream(memoryStream))
                    {
                      
                        byte[] bytes;
    
                    
                          
                            using (var memoryStream1 = new MemoryStream())
                            {
                                image.Save(memoryStream1, GetImageFormat(Path.GetExtension(path)));
                                bytes = memoryStream1.ToArray();
                            }
                        
    
                    }
                }
        }
        
          private ImageFormat GetImageFormat(string extension)
                {
                    switch (extension.ToLower())
                    {
                        case ".png":
                            return ImageFormat.Png;
                        default:
                            return ImageFormat.Jpeg;
                    }
                }