I’m loading an image from a file, and I want to know how to validate the image before it is fully read from the file.
string filePath = 'image.jpg'; Image newImage = Image.FromFile(filePath);
The problem occurs when image.jpg isn’t really a jpg. For example, if I create an empty text file and rename it to image.jpg, an OutOfMemory Exception will be thrown when image.jpg is loaded.
I’m looking for a function that will validate an image given a stream or a file path of the image.
Example function prototype
bool IsValidImage(string fileName); bool IsValidImage(Stream imageStream);
JPEG’s don’t have a formal header definition, but they do have a small amount of metadata you can use.
There are a couple other things after that, but those aren’t important.
You can open the file using a binary stream, and read this initial data, and make sure that OffSet 0 is 0, and OffSet 6 is either 1,2 or 3.
That would at least give you slightly more precision.
Or you can just trap the exception and move on, but I thought you wanted a challenge 🙂