Script for replacing color codes to color names?

Issue

Does anyone know a way to change color codes to color names? I have an XML with color codes:
I need: #FFFFFF to replace to White and #000000 to Black etc.

If you know a script, batch, C# program or anyway to this it ill be greatly appreciated

Thanks 🙂

Solution

Here is a method which will retrieve the name or the RGB value if none is found:

static Color[] colors = typeof(Color)
    .GetProperties(BindingFlags.Public | BindingFlags.Static)
    .Where(pi => pi.CanRead && pi.PropertyType == typeof(Color))
    .Select(pi => (Color)pi.GetValue(null, null))
    .ToArray();

static IEnumerable<string> FindColorNames(string htmlColor)
{
    // like "#RRGGBB" or "#AARRGGBB" or "Red" or "red"
    var color = ColorTranslator.FromHtml(htmlColor);
    return colors.Where(cc => cc.R == color.R
                           && cc.G == color.G
                           && cc.B == color.B
                           && cc.A == color.A)
                 .Select(cc => cc.Name);
}

static string FindColorName(string htmlColor)
{
    return FindColorNames(htmlColor).FirstOrDefault() ?? htmlColor;
}

// #FFFFFF: White
// #000000: Black
// #333333: 333333
// #FF00FF: Fuchsia (Magenta also matches)

An update which uses a nicer search mode:

static Dictionary<int, string[]> colors = static Color[] colors = typeof(Color)
    .GetProperties(BindingFlags.Public | BindingFlags.Static)
    .Where(pi => pi.CanRead && pi.PropertyType == typeof(Color))
    .Select(pi => (Color)pi.GetValue(null, null))
    .GroupBy(cc => cc.ToArgb())
    .ToDictionary(gg => gg.Key, gg.Select(cc => cc.Name).ToArray());

static IEnumerable<string> FindColorNames(string htmlColor)
{
    var color = ColorTranslator.FromHtml(htmlColor);
    string[] names;
    if (!colors.TryGetValue(color.ToArgb(), out names))
    {
        return Enumerable.Empty<string>();
    }

    return names;
}

static string FindColorName(string htmlColor)
{
    return FindColorNames.FirstOrDefault() ?? htmlColor;
}

Answered By – user7116

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.