Rule #1 When Programming With Images
So, something that’s caught me out a number of times now, and something I keep forgetting is the first rule of dealing with images when programming. The Out of memory Exception.
Typically, it means just about anything EXCEPT out of memory with images: Invalid format. Corrupt file. Too big. Not big enough. It’s an elephant, not a file.
In my case, the Out of Memory Exception I was getting actually meant the library I was using was attempting to read a corrupt image. One whose content was a whole two space characters upon Notepad inspection. (artifacts of an error in someone’s save method a while back, perhaps?)
For now, I’ve added in a basic check to remedy this:
private static bool IsValidImage(string path)
using (System.Drawing.Image.FromFile(path)) ;
catch (OutOfMemoryException ex) // Invalid Image
// Log, or similiar
catch (Exception ex) // Some other error; eg file doesn't exist
// Handle error accordingly
It’s not the most elegant solution out there; but as a quick and dirty check, it works! I’ll be replacing this with a more memory-effective header-check after I’ve investigated differing image headers and come up with a nicer solution. 🙂Share on Facebook Share on Twitter Share on Pinterest