Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine file type of an image

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.

like image 904
Eric Avatar asked Sep 11 '08 05:09

Eric


People also ask

How can I tell what file type an image is?

Search Google Images by file type Luckily, there's a way within Google to specify that: just type filetype: + the format you need right into the search field with your query. For example, t-rex filetype:jpg.


2 Answers

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 
like image 88
Vinko Vrsalovic Avatar answered Sep 30 '22 21:09

Vinko Vrsalovic


You can use code below without reference of System.Drawing and unnecessary creation of object Image. Also you can use Alex solution even without stream and reference of System.IO.

public enum ImageFormat {     bmp,     jpeg,     gif,     tiff,     png,     unknown }  public static ImageFormat GetImageFormat(Stream stream) {     // see http://www.mikekunz.com/image_file_header.html     var bmp = Encoding.ASCII.GetBytes("BM");     // BMP     var gif = Encoding.ASCII.GetBytes("GIF");    // GIF     var png = new byte[] { 137, 80, 78, 71 };    // PNG     var tiff = new byte[] { 73, 73, 42 };         // TIFF     var tiff2 = new byte[] { 77, 77, 42 };         // TIFF     var jpeg = new byte[] { 255, 216, 255, 224 }; // jpeg     var jpeg2 = new byte[] { 255, 216, 255, 225 }; // jpeg canon      var buffer = new byte[4];     stream.Read(buffer, 0, buffer.Length);      if (bmp.SequenceEqual(buffer.Take(bmp.Length)))         return ImageFormat.bmp;      if (gif.SequenceEqual(buffer.Take(gif.Length)))         return ImageFormat.gif;      if (png.SequenceEqual(buffer.Take(png.Length)))         return ImageFormat.png;      if (tiff.SequenceEqual(buffer.Take(tiff.Length)))         return ImageFormat.tiff;      if (tiff2.SequenceEqual(buffer.Take(tiff2.Length)))         return ImageFormat.tiff;      if (jpeg.SequenceEqual(buffer.Take(jpeg.Length)))         return ImageFormat.jpeg;      if (jpeg2.SequenceEqual(buffer.Take(jpeg2.Length)))         return ImageFormat.jpeg;      return ImageFormat.unknown; } 
like image 22
Ivan Kochurkin Avatar answered Sep 30 '22 21:09

Ivan Kochurkin