C#ImageFormat为字符串

如何从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 _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; } 

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

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

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

ImageFormat值由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); } 

图像格式不是很多。 所以你可以使用一个开关,以防你想自己指定你的描述或只是使用

 Imageformat.Specific.ToString() 

(具体是特定图像格式的名称)