C#ImageFormat为字符串

Mic*_*l Z 12 c# image

如何从System.Drawing.ImageFormat对象获取人类可读的字符串(即图像格式本身)?

我的意思是,如果我有ImageFormat.Png可能将其转换为"png"字符串?

编辑:我在这看到一些误解.这是我的代码:

Image objImage = Image.FromStream(file);

ImageFormat imFormat = objImage.RawFormat;

imFormat.ToString(); 
Run Code Online (Sandbox Code Playgroud)

它返回" [ImageFormat: b96b3caf-0728-11d3-9d7b-0000f81ef32e]"但我想要" Png"!

小智 27

使用System.Drawing命名空间中的ImageFormatConverter类:

this.imageInfoLabel.Text = 
    new ImageFormatConverter().ConvertToString(this.Image.RawFormat);
Run Code Online (Sandbox Code Playgroud)

对于PNG图像,它返回Png,依此类推.


Tho*_*que 9

ImageFormat.Png.ToString() 返回"Png"......

编辑:好的,它似乎ToStringImageFormat返回由静态属性返回的实例的名称...

您可以创建一个查找字典以从Guid获取名称:

private static readonly Dictionary<Guid, string> _knownImageFormats =
            (from p in typeof(ImageFormat).GetProperties(BindingFlags.Static | BindingFlags.Public)
             where p.PropertyType == typeof(ImageFormat)
             let value = (ImageFormat)p.GetValue(null, null)
             select new { Guid = value.Guid, Name = value.ToString() })
            .ToDictionary(p => p.Guid, p => p.Name);

static string GetImageFormatName(ImageFormat format)
{
    string name;
    if (_knownImageFormats.TryGetValue(format.Guid, out name))
        return name;
    return null;
}
Run Code Online (Sandbox Code Playgroud)