Assuming ASP.NET and form upload, any way to ensure file is an image?

121 views Asked by At

Is there any way to tell if the file is an image either through MIME type or some other way of inspection? The images are going into a gallery and I'll be resizing them as necessary and want to ensure, to the best I can, that the file I'm about to process with GDI is, in fact, an image.

3

There are 3 answers

0
David On BEST ANSWER

Try to load the file into a Bitmap object. If if you get an exception then it isn't an image.

0
David Glass On

Check out this question/answer on stackoverflow and this one. I belive this is a duplicate question.

Also, look into reading a file's magic number especially if you are just trying to determine if the file is one of a few acceptable types. Magic number Wikipedia

0
James On

Yes, you can check the fileUploadCtrl.PostedFile.ContentType property and compare that string to an expected list of image MIME types i.e. image/gif. You can also perform additional validation by loading the uploaded image bytes into a System.Drawing.Image object. If it loads you know you have a good image, if it fails to load then perhaps the image is a forgery or an unknown format.