I don't want to rely on the file extension. I don't care to know what type of image it is (.jpg, .png, etc.), I simply want to know if the file is an image or not. I'd prefer to not use any non-.NET dlls if possible.
The best way I know how to do this is the following:
bool isImageFile;
try
{
Image.FromFile(imageFile).Dispose();
isImageFile = true;
}
catch (OutOfMemoryException)
{
isImageFile = false;
}
As noted here: http://msdn.microsoft.com/en-us/library/stf701f5.aspx, Image.FromFile()
throws an OutOfMemoryException
if the file isn't a valid image format. Using the above gives me exactly the result I want, however I'd prefer not to use it for the following reasons:
Image.FromFile()
loads the whole image file (if it is an image file) into memory. This is wasteful I assume because I only need the file type and don't need to do any further image manipulation at this point in my code.OutOfMemoryException
s because what if there is a REAL out-of-memory problem and my program swallows it and keeps going?Are there any better ways to do this? Or, are any/all of my concerns listed above unwarranted?
Edit: Since receiving the answers here, these are the three solutions I'm now aware of:
Image.FromFile()
and a try-catch.
(I do not see a clear "winner" since I can imagine a situation in which each one would be appropriate. For my application's purposes, the file type checking happens infrequently enough that the performance concerns of method 1 weren't an issue.)
Search Google Images by file type Luckily, there's a way within Google to specify that: just type filetype: + the format you need right into the search field with your query. For example, t-rex filetype:jpg.
bool CheckFileType(string fileName) { string ext = Path. GetExtension(fileName); switch (ext. ToLower()) { case ". gif": return true; case ".
Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.
If you will only be supporting a handful of the popular image formats, then you can simply read the first few bytes of the file to determine the type based on the Magic Number
Examples from the link provided:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With