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

Comment by Phil Smith

Thanks for this code. Owe you a beer.

Phil Smith
Comment by hina

Thanks!!!

hina
Comment by edward jay

Thanks for your post, vberror12. I think this is just what I'm after.

But 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..


Comment by vberror13

Thanks, i was looking for this codes.

vberror13
Comment by steve

great post. exactly what I needed. I too prefer not to use large switch statements when a small loop can do the trick.

steve
Comment by ddboook

Thanks! Your code is very good!

ddboook