convert hex code to color name
I stumbled upon a german site that does exactly what you want:
/// <summary>
/// Gets the System.Drawing.Color object from hex string.
/// </summary>
/// <param name="hexString">The hex string.</param>
/// <returns></returns>
private System.Drawing.Color GetSystemDrawingColorFromHexString(string hexString)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(hexString, @"[#]([0-9]|[a-f]|[A-F]){6}\b"))
throw new ArgumentException();
int red = int.Parse(hexString.Substring(1, 2), NumberStyles.HexNumber);
int green = int.Parse(hexString.Substring(3, 2), NumberStyles.HexNumber);
int blue = int.Parse(hexString.Substring(5, 2), NumberStyles.HexNumber);
return Color.FromArgb(red, green, blue);
}
To get the color name you can use it as follows to get the KnownColor:
private KnownColor GetColor(string colorCode)
{
Color color = GetSystemDrawingColorFromHexString(colorCode);
return color.GetKnownColor();
}
However, System.Color.GetKnownColor
seems to be removed in newer versions of .NET
Use this method
Color myColor = ColorTranslator.FromHtml(htmlColor);
Also see the link
This can be done with a bit of reflection. Not optimized, but it works:
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);
}