jQuery and ASP.NET

October 31, 2009

Find Out the Image Type without Checking its Extension




My colleague called up with a query. His application accepted images to be uploaded to a central server. Later the application processed the images and separated them according to the Image Type. They determined the image type by checking the extension of the image uploaded –- a very common practice of detecting the image type.

The issue here was that some images which were actually gif’s were renamed as jpeg’s and then uploaded, which led to faulty image processing. The requirement was to determine the correct image type in the simplest possible way even if the extension was renamed. Here’s what I suggested:

C#

try
{
Image imgUp = Image.FromFile(Server.MapPath("~/images/abc.jpg"));
if (imgUp.RawFormat.Equals(ImageFormat.Jpeg))
Response.Write("JPEG");
else if (imgUp.RawFormat.Equals(ImageFormat.Gif))
Response.Write("GIF");
}
catch (Exception ex)
{
}

VB.NET

Try
Dim
imgUp As Image = Image.FromFile(Server.MapPath("~/images/abc.jpg"))
If imgUp.RawFormat.Equals(ImageFormat.Jpeg) Then
Response.Write("JPEG")
ElseIf imgUp.RawFormat.Equals(ImageFormat.Gif) Then
Response.Write("GIF")
End If
Catch
ex As Exception
End Try

The Image.RawFormat property is extremely useful in this situation to get the file format of the image.

Note: Alternatively you can also use Magic Numbers



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Find Out the Image Type without Checking its Extension"
 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions