tags:

views:

2520

answers:

2

I am loading the binary bytes of the image file hard drive and loading it into a Bitmap object. How do i find the image type[JPEG, PNG, BMP etc] from the Bitmap object?

Looks trivial. But, couldn't figure it out!

Is there an alternative approach?

Appreciate your response.

UPDATED CORRECT SOLUTION:

@CMS: Thanks for the correct response!

Sample code to achieve this.

        using (MemoryStream imageMemStream = new MemoryStream(fileData))
        {
            using (Bitmap bitmap = new Bitmap(imageMemStream))
            {
                ImageFormat imageFormat = bitmap.RawFormat;
                if (bitmap.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
                    //It's a JPEG;
                else if (bitmap.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
                    //It's a PNG;
            }
        }
+4  A: 

Simply speaking you can't. The reason why is that Bitmap is a type of image in the same way that JPEG, PNG, etc are. Once you load a image into a Bitmap the image of the bitmap format. There is no way to look at a bitmap and understand the original encoding of the image (if it's even different than Bitmap).

JaredPar
+11  A: 

If you want to know the format of an image, you can load the file with the Image class, and check its RawFormat property:

using(Image img = Image.FromFile(@"C:\path\to\img.jpg"))
{
    if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
    {
      // ...
    }
}
CMS
Works perfect!
pencilslate