我得到了用C#工作的代碼。我想幫助將其轉換爲慣用的PowerShell腳本,該腳本將rgb或十六進制顏色定義作爲輸入,並將包含顏色名稱和rgb值的前3或5個匹配輸出到控制檯。我對PowerShell很新,很抱歉,如果這太要求了。使用PowerShell查找最接近的System.Color實例
private static void FindMyColor()
{
System.Drawing.Color targetColor = System.Drawing.Color.FromArgb(red: 0, green: 128, blue: 0);
var myStuff = EnumerateColors(targetColor: targetColor).OrderBy(tpl => tpl.Item1).ToList();
int a = 0; // Pause the debugger here.
}
private static double GetColorDistance(System.Drawing.Color lhs, System.Drawing.Color rhs)
{
double sum = Cube(lhs.R - rhs.R) + Cube(lhs.G - rhs.G) + Cube(lhs.B - rhs.B);
return Math.Pow(sum, 1.0/3.0);
}
private static double Cube(int value)
{
return (double) (value * value * value);
}
private static System.Collections.Generic.IEnumerable<Tuple<double, string, System.Drawing.Color>> EnumerateColors(System.Drawing.Color targetColor)
{
var candidateColors = EnumerateSystemColors();
foreach (string colorName in candidateColors.Keys)
{
var color = candidateColors[key: colorName];
double colorDistance = GetColorDistance(lhs: color, rhs: targetColor);
yield return new Tuple<double, string, System.Drawing.Color>(colorDistance, colorName, color);
}
}
private static System.Collections.Generic.Dictionary<string, System.Drawing.Color> EnumerateSystemColors()
{
var properties = typeof(System.Drawing.Color)
.GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy);
return properties.ToDictionary(p => p.Name, p => (System.Drawing.Color)p.GetValue(null, null));
}
這很酷,謝謝! – 2012-08-06 16:33:44