Get the MIME type of a System.Drawing Image
January 17. 2008 6 Comments
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 stringGetMimeType(Imagei)
{
foreach (ImageCodecInfo codec inImageCodecInfo.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).
Comments
Thanks for this code. Owe you a beer.
Phil SmithThanks!!!
hinaThanks for your post, vberror12. I think this is just what I'm after.
edward jayBut excuse my ignorance.could you please clarify how I make the link between
System.Drawing.Imaging.RawFormat.Guid
and the original call to the image ie.
Dim fullSizeImg as System.Drawing.Image = System.Drawing.Image.FromFile(fullpath)
Many thanks..
Thanks, i was looking for this codes.
vberror13great post. exactly what I needed. I too prefer not to use large switch statements when a small loop can do the trick.
steveThanks! Your code is very good!
ddboook