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...
Look into Color.ToARGB()
http://msdn.microsoft.com/en-us/library/system.drawing.color.toargb.aspx
If you will convert the color back with {ColorTranslator.FromHTML}, 'White' is a valid string for a HTML color. But I've found that this implementation needs a # symbol before the string that represents the color if it isn't common (for example, it works with White, and #FFFFFF, but it doesn't with #White or FFFFFF). So I tried putting the conversion inside a try/catch block, made the conversion adding '#'to the string and if it threw an exception then I caught it and made the conversion without #.
"White" is a valid HTML color. Please see
ColorTranslator.ToHtml
:If your color cannot be mapped to a HTML color string this method will return the valid hex for the color. See this example:
Something like :
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 :
Usage :
I have written my own .net extension for simple converting from hex to integer and integer(ARGB) to color and vise versa: