views:

1945

answers:

4

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.

A: 

Try loading the stream into a System.IO.BinaryReader.

Then you will need to refer to the specifications for each image format you need, and load the header byte by byte to compare against the specifications. For example here are the PNG specifications

Added: The actual file structure for PNG.

Ash
+10  A: 

All the image formats set their initial bytes to a particular value:

Search for "jpg file format" replacing jpg with the other file formats you need to identify.

As Garth recommends, there is a database of such 'magic numbers' showing the file type of many files. If you have to detect a lot of different file types it's worthwhile looking through it to find the information you need. If you do need to extend this to cover many, many file types, look at the associated file command which implements the engine to use the database correctly (it's non trivial for many file formats, and is almost a statistical process)

Adam Davis
+5  A: 
Garth T Kidd
+20  A: 

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
Vinko Vrsalovic
For what I needed, this did the trick perfectly. Thanks!
Eric Willis
FYI, this also works for streams using System.Drawing.Image.FromStream()
jishi
Exactly what i was looking for +1
almog.ori