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; } }
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)) { // ... } }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With