0

Can anyone tell me what is wrong with the below code i am having no joy figuring this out. I am disposing and have in a using block but keep getting this exception

An unhandled exception of type 'System.OutOfMemoryException' occurred in System.Drawing.dll

Additional information: Out of memory.

foreach (FileInfo file in files)
{
    Regex re = new Regex("original", RegexOptions.IgnoreCase);
    if (re.IsMatch(file.FullName)) continue;

    using (System.Drawing.Image img = System.Drawing.Image.FromFile(file.FullName))
    {
        if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
        {
            filesJpeg.Add(file);
            img.Dispose();
        }
        else
        {
            img.Dispose();
            File.Delete(file.FullName);
        }
 
        img.Dispose();
    }
}
Community
  • 1
  • 1
user1853454
  • 131
  • 1
  • 4
  • 12
  • 1
    Why you are disposing img inside `using` block. It will automatically done after `using` call ends – Avijit Dec 28 '14 at 11:27
  • I had no disposing and was getting the error as didnt think was neccessary so added also and still got same error. – user1853454 Dec 28 '14 at 11:40
  • Which line you got the exception – Avijit Dec 28 '14 at 11:43
  • System.Drawing.Image img = System.Drawing.Image.FromFile(file.FullName) – user1853454 Dec 28 '14 at 11:44
  • See here http://stackoverflow.com/questions/16842708/out-of-memory-on-loading-a-image-with-system-drawing-image http://stackoverflow.com/questions/1108607/out-of-memory-exception-on-system-drawing-image-fromfile – Avijit Dec 28 '14 at 11:46

1 Answers1

1

The OutOfMemoryException when opening images might not necessarily mean it's out of memory. It may mean the image format is unknown, or not supported by GDI+ .

As per the documentation (on http://msdn.microsoft.com/en-us/library/stf701f5.aspx):

Exception

OutOfMemoryException

Condition

The file does not have a valid image format.

-or-

GDI+ does not support the pixel format of the file.

I'd check the file where it's throwing the exception and see if it's in a strange format

Community
  • 1
  • 1
Jcl
  • 27,696
  • 5
  • 61
  • 92