04 December 2008

Converting colors from RGB to HTML and back

A very short one this time: it turns out to be pretty easy to convert a RGB color to a HTML color and back. This may come handy when (like me) you are using configuration files in which colors for map features are specified in RGB. Add a reference to System.Drawing.dll and a "using System.Drawing" to your class and you can use the following code:
Color rgbColor = Color.FromArgb(255, 0, 0);
string HTMLColor = ColorTranslator.ToHtml(rgbColor);
Color rgbColor2 = ColorTranslator.FromHtml(HTMLColor);
Color rgbColor3 = ColorTranslator.FromHtml("Fuchsia");

     rgbColor2.R, rgbColor2.G, rgbColor2.B));
     rgbColor3.R, rgbColor3.G, rgbColor3.B));
this wil output the following: #FF0000 255,0,0 255,0,255 I translated RGB red to HTML red, and back. For an encore, I demonstrated the fact that named colors are translated into RGB as well.

No comments: