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#

3
  • What you need it for? Seeing the bigger picture might help us help you better. Commented Oct 17, 2011 at 9:28
  • 3
    Who says that #2088C1 is aqua blue? Commented Oct 17, 2011 at 9:30
  • possible duplicate of How to get Color from Hexadecimal color code using .NET? Commented Dec 16, 2013 at 11:49

9 Answers 9

8

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

Sign up to request clarification or add additional context in comments.

7 Comments

thanks,but it was showing like this "ff2088C1" but i want to know the equivalent colour name like blue or red from that code
i am not able yo get the color.GetKnownColor();
The KnownColor structure represents system color settings like ActiveCaptionText not a color name itself
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.
@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.
|
7

Use this method

Color myColor = ColorTranslator.FromHtml(htmlColor);

Also see the link

1 Comment

thanks but i want to know the equivalent colour name like blue or red from that code
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);
}

1 Comment

Just a little edit: it's colorProperty that has the Name not the colorPropertyValue. Thanks for the solution
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 ());
}

Comments

1

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

Comments

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

Comments

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.

Comments

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"/>

Comments

-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.