Find Out the Image Type without Checking its Extension using C#

Question is...
Find Out the Image Type without Checking its Extension using C#

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:


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)
{
}

Leave a Reply