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.
Asked
Active
Viewed 2,255 times
2 Answers
6
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;
}

Samuel Neff
- 73,278
- 17
- 138
- 182
2
https://stackoverflow.com/a/7792104/224370 explains how to match a named color to an exact RGB value. To make it approximate you need some kind of distance function where you calculate how far apart the colors are. Doing this in RGB space (sum of squares of differences in R, G and B values) isn't going to give you a perfect answer (but may well be good enough). See https://stackoverflow.com/a/7792111/224370 for an example that does it that way. To get a more precise answer you might need to convert to HSL and then compare.

Community
- 1
- 1

Ian Mercer
- 38,490
- 8
- 97
- 133