这里有一些基于Ian建议的代码.我在一些颜色值上测试它,似乎运作良好.
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;
}
Run Code Online (Sandbox Code Playgroud)
/sf/answers/545447311/解释了如何将命名颜色与精确的 RGB 值相匹配。为了使其近似,您需要某种距离函数来计算颜色之间的距离。在 RGB 空间(R、G 和 B 值差异的平方和)中执行此操作不会给您一个完美的答案(但可能已经足够好了)。有关这样做的示例,请参阅/sf/answers/545447801/ 。要获得更准确的答案,您可能需要转换为 HSL 然后进行比较。