C# ImageFormat to string

前端 未结 4 1639
灰色年华
灰色年华 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:33

    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);
    }
    
    0 讨论(0)
  • 2021-02-07 23:42

    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.

    0 讨论(0)
  • 2021-02-07 23:54

    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)

    0 讨论(0)
  • 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<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;
    }
    
    0 讨论(0)
提交回复
热议问题