FIND IMAGE FORMAT USING BITMAP OBJECT IN C#

Samuel Fernandes

Total Post:159

Points:1117
Posted by  Samuel Fernandes
C# 
C#
 1724  View(s)
Ratings:
Rate this:

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!

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;

    }

}

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Find image format using Bitmap object in C#

    Hi Samuel,


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

        {

          // ...

        }

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!