Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the name of color through Hex Value?

Tags:

c#

colors

I know how to get the name of predefined colors using hex value but how to to get the name of color while approximating its Hex valueto the closest known color.

like image 735
fresky Avatar asked Jul 31 '12 19:07

fresky


People also ask

How hexadecimal is used to identify colors?

Hex color codes start with a pound sign or hashtag (#) and are followed by six letters and/or numbers. The first two letters/numbers refer to red, the next two refer to green, and the last two refer to blue. The color values are defined in values between 00 and FF (instead of from 0 to 255 in RGB).

Do hex Colours have names?

There are over 1,500 color names available, ranging from alabaster to zinnwaldite. Others are more common, such as brick red, chocolate, and slate gray. Even if you don't land on a perfect match, the nearest named-color is only a shade or two away.

How do you extract a hex color?

If you want to find hex code of color on the screen, you need to right-click the icon in the taskbar and select Hex. Next, you need to click the icon again and move the tool to the color you want to pick on the screen. Then, you can see the hex code of the color. Remember it and you can use it in your design.


1 Answers

Here's some code based on Ian's suggestion. I tested it on a number of color values, seems to work well.

GetApproximateColorName(ColorTranslator.FromHtml(source))

private static readonly IEnumerable<PropertyInfo> _colorProperties = 
            typeof(Color)
            .GetProperties(BindingFlags.Public | BindingFlags.Static)
            .Where(p => p.PropertyType == typeof (Color));

static string GetApproximateColorName(Color color)
{
    int minDistance = int.MaxValue;
    string minColor = Color.Black.Name;

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

        int distance = Math.Abs(colorPropertyValue.R - color.R) +
                        Math.Abs(colorPropertyValue.G - color.G) +
                        Math.Abs(colorPropertyValue.B - color.B);

        if (distance < minDistance)
        {
            minDistance = distance;
            minColor = colorPropertyValue.Name;
        }
    }

    return minColor;
}
like image 200
Samuel Neff Avatar answered Oct 12 '22 22:10

Samuel Neff