C# ImageFormat to string

前端 未结 4 1645
灰色年华
灰色年华 2021-02-07 23:24

How can I obtain human readable string(i.e. image format itself) from System.Drawing.ImageFormat object?

I mean if I have ImageF

4条回答
  •  难免孤独
    2021-02-07 23:56

    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 _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;
    }
    

提交回复
热议问题