Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert hex code to color name

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#

like image 903
Glory Raj Avatar asked Oct 17 '11 09:10

Glory Raj


1 Answers

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

like image 168
PVitt Avatar answered Nov 06 '22 15:11

PVitt