How can I obtain human readable string(i.e. image format itself) from System.Drawing.ImageFormat object?
I mean if I have ImageF
ImageFormat values are identified by Guid you need to create your own map of 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);
}
Use the ImageFormatConverter class from the System.Drawing namespace:
this.imageInfoLabel.Text =
new ImageFormatConverter().ConvertToString(this.Image.RawFormat);
For a PNG image it returns Png, and so on.
There are not so many Image formats. So you can use a switch in case you want to specify your descriptions yourself or just use the
Imageformat.Specific.ToString()
(specific is the name of the specific image format)
ImageFormat.Png.ToString()
returns "Png"...
EDIT: OK, it seems ToString
returns the name only for ImageFormat
instances returned by the static properties...
You could create a lookup dictionary to get the name from the 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;
}