Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find image format using Bitmap object in C#

Tags:

c#

.net

image

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;     } } 
like image 663
pencilslate Avatar asked Sep 09 '09 04:09

pencilslate


2 Answers

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))     {       // ...     } } 
like image 180
Christian C. Salvadó Avatar answered Oct 07 '22 00:10

Christian C. Salvadó


Here is my extension method. Hope this help someone.

public static System.Drawing.Imaging.ImageFormat GetImageFormat(this System.Drawing.Image img)     {                      if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))             return System.Drawing.Imaging.ImageFormat.Jpeg;         if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp))             return System.Drawing.Imaging.ImageFormat.Bmp;         if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))             return System.Drawing.Imaging.ImageFormat.Png;         if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Emf))             return System.Drawing.Imaging.ImageFormat.Emf;         if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Exif))             return System.Drawing.Imaging.ImageFormat.Exif;         if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))             return System.Drawing.Imaging.ImageFormat.Gif;         if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Icon))             return System.Drawing.Imaging.ImageFormat.Icon;         if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.MemoryBmp))             return System.Drawing.Imaging.ImageFormat.MemoryBmp;         if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff))             return System.Drawing.Imaging.ImageFormat.Tiff;         else             return System.Drawing.Imaging.ImageFormat.Wmf;                 } 
like image 33
sebacipo Avatar answered Oct 06 '22 23:10

sebacipo