How to get contentType from System.Drawing.Imaging.ImageFormat

If I have a bitmap and it has a RawFormat property.

How can I get the Content Type from this ImageFormat object?

Bitmap image = new Bitmap(stream); ImageFormat imageFormat = image.RawFormat; //string contentType = ? 
+4
source share
2 answers

I believe that I came up with a simple solution that works great for images. This uses extension methods and Linq, so it will work on the .net framework 3.5+. Here's the code and unit test:

 public static string GetMimeType(this Image image) { return image.RawFormat.GetMimeType(); } public static string GetMimeType(this ImageFormat imageFormat) { ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); return codecs.First(codec => codec.FormatID == imageFormat.Guid).MimeType; } [TestMethod] public void can_get_correct_mime_type() { Assert.AreEqual("image/jpeg", ImageFormat.Jpeg.GetMimeType()); Assert.AreEqual("image/gif", ImageFormat.Gif.GetMimeType()); Assert.AreEqual("image/png", ImageFormat.Png.GetMimeType()); } 
+28
source

If you want to determine the MIME type from the file name (or extension), here is the link that uses the registry: Get MimeType from the file name

+1
source

All Articles