2012-07-31 49 views

回答

2

https://stackoverflow.com/a/7792104/224370解释了如何将指定的颜色与精确的RGB值进行匹配。为了使其近似,需要某种距离函数来计算颜色的距离。在RGB空间(R,G和B值差异的平方和)做这件事不会给你一个完美的答案(但可能足够好)。有关这样做的示例,请参见https://stackoverflow.com/a/7792111/224370。要获得更准确的答案,您可能需要转换为HSL,然后进行比较。

5

下面是一些基于伊恩建议的代码。我测试了一些颜色值,似乎运作良好。

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

Thankyou so muh Kartan ... :) – fresky 2012-07-31 21:10:54

相关问题