I have a simple program that iterates through a list of images, checks the width and height of the images, and then moves them to a specified folder depending on the outcome. I'm using Image.FromFile(path)
to check the images, and once it hits specific images I get an OutOfMemoryException
.
This potential causes for this error have already been discussed here
string directory = @"C:\foo\bar\";
foreach (string path in Directory.EnumerateFiles(directory, "*", SearchOption.TopDirectoryOnly)
.Where(s => s.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || s.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)))
{
//exception thrown here, at Image.FromFile
Image i = Image.FromFile(path);
if (i.Width > i.Height)
{
i.Dispose();
File.Move(path, directory + @"horizontal\" + path.Substring(path.LastIndexOf(@"\") + 1));
}
else
{
i.Dispose();
File.Move(path, directory + @"vertical\" + path.Substring(path.LastIndexOf(@"\")));
}
}
I know for certain the cause of the error, some of the TIFF images it's hitting (for some absurd reason!) have a bit depth of 40, which is not a valid GDI+ pixel format, here for reference.
I can get around the problem with try-catch (OutOfMemoryException
), but I'd much check the images for a valid pixel format rather than hope I don't get the exception for any other reason.