从System.Drawing.Image.RawFormat获取ImageFormat

Ben*_*ter 10 c# system.drawing system.drawing.imaging

尝试呼叫时此代码失败Image.Save(MemoryStream, ImageFormat).

我得到了例外:

a值不能为null.参数名称:encoder"

ImageFormat format = generatedImage.RawFormat as ImageFormat;
image.ImageData = generatedImage.Save(format);
Run Code Online (Sandbox Code Playgroud)

如果我ImageFormat直接传入一个对象,它就可以工作了ImageFormat.Jpeg.

什么是转换的最佳途径rawformat,以ImageFormat(最理想的情况switch语句或大量的if语句)

谢谢Ben

Che*_*rek 16

我使用以下的hepler方法:

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";
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*tke 9

对不起,我发现没有可能直接从解析或生成的Image对象中提取"正确的"ImageFormat.

这是我的代码,您可以通过存储静态ImageFormat成员而不是mimetype来采用它.

                if (image.RawFormat.Equals(ImageFormat.Jpeg))
                    binary.MetaInfo.Mimetype = "image/jpeg";
                else if (image.RawFormat.Equals(ImageFormat.Bmp))
                    binary.MetaInfo.Mimetype = "image/bmp";
                else if (image.RawFormat.Equals(ImageFormat.Emf))
                    binary.MetaInfo.Mimetype = "image/emf";
                else if (image.RawFormat.Equals(ImageFormat.Exif))
                    binary.MetaInfo.Mimetype = "image/exif";
                else if (image.RawFormat.Equals(ImageFormat.Gif))
                    binary.MetaInfo.Mimetype = "image/gif";
                else if (image.RawFormat.Equals(ImageFormat.Icon))
                    binary.MetaInfo.Mimetype = "image/icon";
                else if (image.RawFormat.Equals(ImageFormat.Png))
                    binary.MetaInfo.Mimetype = "image/png";
                else if (image.RawFormat.Equals(ImageFormat.Tiff))
                    binary.MetaInfo.Mimetype = "image/tiff";
                else if (image.RawFormat.Equals(ImageFormat.Wmf))
                    binary.MetaInfo.Mimetype = "image/wmf";
Run Code Online (Sandbox Code Playgroud)

您可以通过使用静态ImageFormat成员数组来整理它,但我认为您将无法避免切换或循环.

最好的问候,马蒂亚斯


小智 6

你在找这个吗?


System.Drawing.Imaging.ImageFormat fmt = new System.Drawing.Imaging.ImageFormat(generatedImage.RawFormat.Guid);
Run Code Online (Sandbox Code Playgroud)