C# 将ImageFormat转换为字符串

C# 将ImageFormat转换为字符串,c#,image,C#,Image,如何获得人类可读的stringi.e。是否从System.Drawing.ImageFormat对象设置图像格式本身 我的意思是,如果我有ImageFormat.Png,是否可以将其转换为Png字符串 编辑:我在这里看到一些误解。这是我的密码: Image objImage = Image.FromStream(file); ImageFormat imFormat = objImage.RawFormat; imFormat.ToString(); 它返回[ImageFormat:b9

如何获得人类可读的stringi.e。是否从System.Drawing.ImageFormat对象设置图像格式本身

我的意思是,如果我有ImageFormat.Png,是否可以将其转换为Png字符串

编辑:我在这里看到一些误解。这是我的密码:

Image objImage = Image.FromStream(file);

ImageFormat imFormat = objImage.RawFormat;

imFormat.ToString(); 
它返回[ImageFormat:b96b3caf-0728-11d3-9d7b-0000f81ef32e],但我想要Png

ImageFormat.Png.ToString返回Png

编辑:好的,似乎ToString只返回静态属性返回的ImageFormat实例的名称

您可以创建查找字典以从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;
}

没有那么多的图像格式。因此,如果您想自己指定描述或仅使用

Imageformat.Specific.ToString()

specific是特定图像格式的名称

图像格式值由Guid标识。您需要创建自己的Guid->name映射

var dict = (
    from t in typeof(ImageFormat).GetProperties()
    where t.PropertyType == typeof(ImageFormat)
    let v = (ImageFormat)t.GetValue(null, new object[0])
    select new { v.Guid, t.Name }
    ).ToDictionary(g => g.Guid, g => g.Name);

string name;
if (dict.TryGetValue(ImageFormat.Png.Guid, out name))
{
    Console.WriteLine(name);
}
使用System.Drawing命名空间中的类:

this.imageInfoLabel.Text = 
    new ImageFormatConverter().ConvertToString(this.Image.RawFormat);

对于PNG图像,它会返回PNG,依此类推。

@MichaelZ,请参阅我更新的答案,该答案不起作用,因为我对ImageFormat有编译时参考。在我的原始问题中查看我的编辑哇!对于C新手来说,解决方案太难了。我最好在这里使用Equals。。。但是无论如何谢谢你!伟大的解决方案!遗憾的是,这不是现成的图像格式。工作完美!又好又容易。谢谢