2012-07-31 111 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

相關問題