Convert Hex color code to color name (string)

I want to convert a hexadecimal color code to a suitable string color name ... with the following code, I managed to get the hexadecimal code of the β€œmost used” color in the photo:

class ColorMath
{
    public static string getDominantColor(Bitmap bmp)
    {
        //Used for tally
        int r = 0;
        int g = 0;
        int b = 0;

        int total = 0;

        for (int x = 0; x < bmp.Width; x++)
        {
            for (int y = 0; y < bmp.Height; y++)
            {
                Color clr = bmp.GetPixel(x, y);

                r += clr.R;
                g += clr.G;
                b += clr.B;

                total++;
            }
        }

        //Calculate average
        r /= total;
        g /= total;
        b /= total;

        Color myColor = Color.FromArgb(r, g, b);
        string hex = myColor.R.ToString("X2") + myColor.G.ToString("X2") + myColor.B.ToString("X2");

        return hex;
    }
}

So, I want for the hex code: # 3A322B something like "dark brown" to appear

+4
source share
1 answer

Assuming the color is in KnownColorenum, you can use ToKnownColor:

KnownColor knownColor = color.ToKnownColor();

Note the following from the MSDN docs:

ToKnownColor , FromArgb, ToKnownColor 0, ARGB ARGB .

, , - :

Color color = (Color)new ColorConverter().ConvertFromString(htmlString);

htmlString #RRGGBB.

KnownColor , ToString (. ):

string name = knownColor.ToString();

, :

string GetColourName(string htmlString)
{
    Color color = (Color)new ColorConverter().ConvertFromString(htmlString);
    KnownColor knownColor = color.ToKnownColor();

    string name = knownColor.ToString();
    return name.Equals("0") ? "Unknown" : name;
}

:

string name = GetColourName("#00FF00");

Lime.

, , , , html:

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);
}
+2

Source: https://habr.com/ru/post/1662407/


All Articles