Determine file type of an image

Eric picture Eric · Sep 11, 2008 · Viewed 29.3k times · Source

I'm downloading some images from a service that doesn't always include a content-type and doesn't provide an extension for the file I'm downloading (ugh, don't ask).

What's the best way to determine the image format in .NET?

The application that is reading these downloaded images needs to have a proper file extension or all hell breaks loose.

Answer

Vinko Vrsalovic picture Vinko Vrsalovic · Sep 11, 2008

A probably easier approach would be to use Image.FromFile() and then use the RawFormat property, as it already knows about the magic bits in the headers for the most common formats, like this:

Image i = Image.FromFile("c:\\foo");
if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(i.RawFormat)) 
    MessageBox.Show("JPEG");
else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(i.RawFormat))
    MessageBox.Show("GIF");
//Same for the rest of the formats