views:

1097

answers:

3

As per the question title, How could I take a hex code and convert it to a .Net Color object, and do it the other way?

I googled and keep getting the same way which doesn't work.

 ColorTranslator.ToHtml(renderedChart.ForeColor)

Which returns the name of the color as in 'White' instead of '#ffffff'! Doing it the other way seems to have odd results, only working some of the time...

+3  A: 

"White" is a valid HTML color. Please see ColorTranslator.ToHtml:

This method translates a Color structure to a string representation of an HTML color. This is the commonly used name of a color, such as "Red", "Blue", or "Green", and not string representation of a numeric color value, such as "FF33AA".

If your color cannot be mapped to a HTML color string this method will return the valid hex for the color. See this example:

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
     Console.WriteLine(ColorTranslator.ToHtml(Color.White));
     Console.WriteLine(ColorTranslator.ToHtml(Color.FromArgb(32,67,89)));
    }
}
Andrew Hare
+8  A: 

Something like :

Color color = Color.Red;
string colorString = string.Format("#{0:X2}{1:X2}{2:X2}",
    color.R, color.G, color.B);

Doing it the other way is a little more complex as #F00 is a valid html color (meaning full red) but it is still doable using regex, here is a small sample class :

using System;
using System.Diagnostics;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Collections.Generic;

public static class HtmlColors
{
    public static string ToHtmlHexadecimal(this Color color)
    {
        return string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
    }

    static Regex htmlColorRegex = new Regex(
        @"^#((?'R'[0-9a-f]{2})(?'G'[0-9a-f]{2})(?'B'[0-9a-f]{2}))"
        + @"|((?'R'[0-9a-f])(?'G'[0-9a-f])(?'B'[0-9a-f]))$",
        RegexOptions.Compiled | RegexOptions.IgnoreCase);

    public static Color FromHtmlHexadecimal(string colorString)
    {
        if (colorString == null)
        {
            throw new ArgumentNullException("colorString");
        }

        var match = htmlColorRegex.Match(colorString);
        if (!match.Success)
        {
            var msg = "The string \"{0}\" doesn't represent"
            msg += "a valid HTML hexadecimal color";
            msg = string.Format(msg, colorString);

            throw new ArgumentException(msg,
                "colorString");
        }

        return Color.FromArgb(
            ColorComponentToValue(match.Groups["R"].Value),
            ColorComponentToValue(match.Groups["G"].Value),
            ColorComponentToValue(match.Groups["B"].Value));
    }

    static int ColorComponentToValue(string component)
    {
        Debug.Assert(component != null);
        Debug.Assert(component.Length > 0);
        Debug.Assert(component.Length <= 2);

        if (component.Length == 1)
        {
            component += component;
        }

        return int.Parse(component,
            System.Globalization.NumberStyles.HexNumber);
    }
}

Usage :

// Display #FF0000
Console.WriteLine(Color.Red.ToHtmlHexadecimal());

// Display #00FF00
Console.WriteLine(HtmlColors.FromHtmlHexadecimal("#0F0").ToHtmlHexadecimal());

// Display #FAF0FE
Console.WriteLine(HtmlColors.FromHtmlHexadecimal("#FAF0FE").ToHtmlHexadecimal());
VirtualBlackFox
This seems like overkill considering the fact that the method the OP is using already does what they need it to do.
Andrew Hare
It doesn't, I need the HEX codes regardless of if is a valid HTML Color. So I need the Hex for White and not 'White'.
Damien
That's why i don't have posted a full parser, as i don't know what is exactly required by the OP... he seem to refuse to use color names for some weird reason... And no API that i known do "Color conversion as HTML does but without ever using standard color names"
VirtualBlackFox
I need to use the HEX codes in order to set a color in a jQuery plugin. Which uses hex to set value. Sorry shoula mentioned it
Damien
A: 

Look into Color.ToARGB()

http://msdn.microsoft.com/en-us/library/system.drawing.color.toargb.aspx

Ian Jacobs