Converting Hex Color Code to Color Name (string)
我要将十六进制颜色代码转换为合适的字符串颜色名称…通过以下代码,我可以获得照片中"最常用"颜色的十六进制代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class ColorMath { public static string getDominantColor(Bitmap bmp) { //Used for tally int r = 0; int g = 0; int b = 0; int total = 0; for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { Color clr = bmp.GetPixel(x, y); r += clr.R; g += clr.G; b += clr.B; total++; } } //Calculate average r /= total; g /= total; b /= total; Color myColor = Color.FromArgb(r, g, b); string hex = myColor.R.ToString("X2") + myColor.G.ToString("X2") + myColor.B.ToString("X2"); return hex; } } |
所以我想要一个十六进制代码,比如:3A322B,看起来像"深棕色"
假设颜色在
1 | KnownColor knownColor = color.ToKnownColor(); |
请注意,以下是来自msdn文档的内容:
When the ToKnownColor method is applied to a Color structure that is created by using the FromArgb method, ToKnownColor returns 0, even if the ARGB value matches the ARGB value of a predefined color.
为了获得你的颜色,你可以使用十六进制代码中的如下内容:
1 |
其中,
要将
1 | string name = knownColor.ToString(); |
把所有这些放在一起,你可以使用这个方法:
1 2 3 4 5 6 7 8 | string GetColourName(string htmlString) { Color color = (Color)new ColorConverter().ConvertFromString(htmlString); KnownColor knownColor = color.ToKnownColor(); string name = knownColor.ToString(); return name.Equals("0") ?"Unknown" : name; } |
称之为:
1 | string name = GetColourName("#00FF00"); |
结果出现
我还找到了一个类似的问题的答案,这个问题似乎也很有效,它使用反射并返回到HTML颜色名称:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 string GetColorName(Color color)
{
var colorProperties = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static)
.Where(p => p.PropertyType == typeof(Color));
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;
}
}
//If unknown color, fallback to the hex value
//(or you could return null,"Unkown" or whatever you want)
return ColorTranslator.ToHtml(color);
}