12

How can i convert this hexa code = #2088C1 into colour name Like Blue or Red

My aim is i want to get the colour name like "blue" for the given hexa code

I have tried the below code but it was not giving any colour name ..

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#2088C1");

Color col = ColorConverter.ConvertFromString("#2088C1") as Color;

but it does not giving the colour name like this "aquablue"

I am using winforms applications with c#

Glory Raj
  • 17,397
  • 27
  • 100
  • 203

9 Answers9

9

I stumbled upon a german site that does exactly what you want:

/// <summary>
/// Gets the System.Drawing.Color object from hex string.
/// </summary>
/// <param name="hexString">The hex string.</param>
/// <returns></returns>
private System.Drawing.Color GetSystemDrawingColorFromHexString(string hexString)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(hexString, @"[#]([0-9]|[a-f]|[A-F]){6}\b"))
        throw new ArgumentException();
    int red = int.Parse(hexString.Substring(1, 2), NumberStyles.HexNumber);
    int green = int.Parse(hexString.Substring(3, 2), NumberStyles.HexNumber);
    int blue = int.Parse(hexString.Substring(5, 2), NumberStyles.HexNumber);
    return Color.FromArgb(red, green, blue);
}

To get the color name you can use it as follows to get the KnownColor:

private KnownColor GetColor(string colorCode)
{
    Color color = GetSystemDrawingColorFromHexString(colorCode);
    return color.GetKnownColor();
}

However, System.Color.GetKnownColor seems to be removed in newer versions of .NET

PVitt
  • 11,500
  • 5
  • 51
  • 85
  • 1
    thanks,but it was showing like this "ff2088C1" but i want to know the equivalent colour name like blue or red from that code – Glory Raj Oct 17 '11 at 09:42
  • i am not able yo get the color.GetKnownColor(); – Glory Raj Oct 17 '11 at 09:50
  • The KnownColor structure represents system color settings like ActiveCaptionText not a color name itself – sll Oct 17 '11 at 09:50
  • Please have a look at the link I provided. It shows the MSDN manual for KnownColor. There are also system defined colors stated to be a value of KnownColor, e.g. Coral or Magenta. – PVitt Oct 17 '11 at 10:06
  • Please note the GetColor function does not compile - there is no GetKnownColor - there is ToKnownColor. Further, even with this change, it still won't work as ToKnownColor will only work if the color was originally created with a KnownColor. – MineR Jul 09 '18 at 06:08
  • @PVitt, a recent question was marked as a duplicate of this one by an admin. So the idea is that it should be corrected, I guess. – MineR Jul 09 '18 at 09:18
  • 1
    @MineR Please go ahead and Fix it. This seems the better way than downvoting. I'm out of .NET for years, so please forgive my ignorance of this particular topic. – PVitt Jul 09 '18 at 12:30
8

Use this method

Color myColor = ColorTranslator.FromHtml(htmlColor);

Also see the link

Prasanth
  • 3,029
  • 31
  • 44
5

This can be done with a bit of reflection. Not optimized, but it works:

string GetColorName(Color color)
{
    var colorProperties = typeof(Color)
        .GetProperties(BindingFlags.Public | BindingFlags.Static)
        .Where(p => p.PropertyType == typeof(Color));
    foreach(var colorProperty in colorProperties) 
    {
        var colorPropertyValue = (Color)colorProperty.GetValue(null, null);
        if(colorPropertyValue.R == color.R 
               && colorPropertyValue.G == color.G 
               && colorPropertyValue.B == color.B) {
            return colorPropertyValue.Name;
        }
    }

    //If unknown color, fallback to the hex value
    //(or you could return null, "Unkown" or whatever you want)
    return ColorTranslator.ToHtml(color);
}
Konamiman
  • 49,681
  • 17
  • 108
  • 138
  • Just a little edit: it's `colorProperty` that has the `Name` not the `colorPropertyValue`. Thanks for the solution – Paras Apr 29 '16 at 10:02
1

I just came up with this:

enum MatchType
{
  NoMatch,
  ExactMatch,
  ClosestMatch
};

static MatchType FindColour (Color colour, out string name)
{
  MatchType
    result = MatchType.NoMatch;

  int
    least_difference = 0;

  name = "";

  foreach (PropertyInfo system_colour in typeof (Color).GetProperties (BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy))
  {
    Color
      system_colour_value = (Color) system_colour.GetValue (null, null);

    if (system_colour_value == colour)
    {
      name = system_colour.Name;
      result = MatchType.ExactMatch;
      break;
    }

    int
      a = colour.A - system_colour_value.A,
      r = colour.R - system_colour_value.R,
      g = colour.G - system_colour_value.G,
      b = colour.B - system_colour_value.B,
      difference = a * a + r * r + g * g + b * b;

    if (result == MatchType.NoMatch || difference < least_difference)
    {
      result = MatchType.ClosestMatch;
      name = system_colour.Name;
      least_difference = difference;
    }
  }

  return result;
}

static void Main (string [] args)
{
  string
    colour;

  MatchType
    match_type = FindColour (Color.FromArgb (0x2088C1), out colour);

  Console.WriteLine (colour + " is the " + match_type.ToString ());

  match_type = FindColour (Color.AliceBlue, out colour);

  Console.WriteLine (colour + " is the " + match_type.ToString ());
}
Skizz
  • 69,698
  • 10
  • 71
  • 108
0

This is an old post but here's an optimised Color to KnownColor converter, as the built in .NET ToKnownColor() doesn't work correctly with adhoc Color structs. The first time you call this code it will lazy-load known color values and take a minor perf hit. Sequential calls to the function are a simple dictionary lookup and quick.

public static class ColorExtensions
{
    private static Lazy<Dictionary<uint, KnownColor>> knownColors = new Lazy<Dictionary<uint, KnownColor>>(() =>
    {
        Dictionary<uint, KnownColor> @out = new Dictionary<uint, KnownColor>();
        foreach (var val in Enum.GetValues(typeof(KnownColor)))
        {
            Color col = Color.FromKnownColor((KnownColor)val);
            @out[col.PackColor()] = (KnownColor)val;
        }
        return @out;
    });

    /// <summary>Packs a Color structure into a single uint (argb format).</summary>
    /// <param name="color">The color to package.</param>
    /// <returns>uint containing the packed color.</returns>
    public static uint PackColor(this Color color) => (uint)((color.A << 24) | (color.R << 16) | (color.G << 8) | (color.B << 0));

    /// <summary>Unpacks a uint containing a Color structure.</summary>
    /// <param name="color">The color to unpackage.</param>
    /// <returns>A new Color structure containing the color defined by color.</returns>
    public static Color UnpackColor(this uint color) => Color.FromArgb((byte)(color >> 24), (byte)(color >> 16), (byte)(color >> 8), (byte)(color >> 0));

    /// <summary>Gets the name of the color</summary>
    /// <param name="color">The color to get the KnownColor for.</param>
    /// <returns>A new KnownColor structure.</returns>
    public static KnownColor? GetKnownColor(this Color color)
    {
        KnownColor @out;
        if (knownColors.Value.TryGetValue(color.PackColor(), out @out))
            return @out;

        return null;
    }
}
Rob
  • 1,687
  • 3
  • 22
  • 34
0

If you are looking to get the name of the color, you can do this without the step of converting the color to hex via:

Color c = (Color) yourColor;

yourColor.Color.Tostring;

Then remove the unwanted symbols that are returned, most of the time if your color is undefined it will return an ARGB value which in that case there is no built in names, but it does have many name values included.

Also, ColorConverter is a good way to convert from hex to name if you need to have the hex code at all.

sschale
  • 5,168
  • 3
  • 29
  • 36
0

made a wpf string to color converter since I needed one:

     class StringColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        string colorString = value.ToString();
        //Color colorF = (Color)ColorConverter.ConvertFromString(color); //displays r,g ,b values
        Color colorF = ColorTranslator.FromHtml(colorString);
        return colorF.Name;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

usable with

          <TextBlock Width="40" Height="80" Background="DarkViolet" Text="{Binding Background, Converter={StaticResource StringColorConverter}, Mode=OneWay, RelativeSource={RelativeSource Self}}" Foreground="White" FontWeight="SemiBold"/>
Nyalotha
  • 369
  • 3
  • 8
0

There is no ready made function for this. You will have to run through the list of known colors and compare RGB of each known color with your unknown's RGB.

Check out this link: http://bytes.com/topic/visual-basic-net/answers/365789-argb-color-know-color-name

Dialecticus
  • 16,400
  • 7
  • 43
  • 103
-1

If you have access to SharePoint assemblies, Microsoft.SharePoint contains a class Microsoft.SharePoint.Utilities.ThemeColor with a static method GetScreenNameForColor which takes a System.Drawing.Color object and returns a string describing it. There's about 20 different color names with light and dark variations it can return.

Rawling
  • 49,248
  • 7
  • 89
  • 127