I needed a method to get the mime type of a System.Drawing Image instance that I'd loaded from an upload. All articles I was able to find online suggest some kind of lookup table solution. There's actually another way. Given an Image i, you can map from the i.RawFormat.Guid property to an ImageCodecInfo.FormatID. So it becomes a very simple for loop to get the MIME type of an image or bitmap. This works for any format System.Drawing/GDI+ supports (bmp, png, tiff, jpg/jpeg, etc). Here's the code:
public static string GetMimeType(Image i)
{
foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageDecoders())
{
if (codec.FormatID == i.RawFormat.Guid)
return codec.MimeType;
}
return "image/unknown";
}
This won't work for images that were created on the fly (will return "image/unknown"), but will work for all images that were loaded from some source (file, stream, byte[], etc).