Get ImageFormat from System.Drawing.Image.RawFormat

Ben Foster picture Ben Foster · Nov 26, 2010 · Viewed 29.4k times · Source

This code fails when trying to call Image.Save(MemoryStream, ImageFormat).

I get the exception:

a Value cannot be null.Parameter name: encoder"

ImageFormat format = generatedImage.RawFormat as ImageFormat;
image.ImageData = generatedImage.Save(format);

It works if I pass in an ImageFormat object directly e.g. ImageFormat.Jpeg.

What is the best way of converting the rawformat to ImageFormat (ideally without a switch statement or lots of if statements)

Thanks Ben

Answer

Cheburek picture Cheburek · Jun 13, 2011

I use following hepler method for the same:

public static string GetMimeType(Image i)
{
    var imgguid = i.RawFormat.Guid;
    foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageDecoders()) 
    {
        if (codec.FormatID == imgguid)
            return codec.MimeType;
    }
    return "image/unknown";
}