I ran into an issue today where I needed to convert an RGB (red,
green, blue) color value set into a hexadecimal code. This seemed
like it should be an easy task, but the first few posts I ran into
online used proprietary code to produce the same effect.
These solutions would work well, but I also remembered that in
the past I have been able to easily create .Net Color structures
using the following code:
System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml("#435b9c");
The
System.Drawing.ColorTranslator class provides several useful
methods for dealing with color conversion. The method I needed was
the inverse of the above example, the
ToHtml method. This method takes a .Net
Color structure and returns the hexadecimal color code as a
string object:
string htmlString = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.Beige);
This is an easy conversion method, but it still doesn't provide
a single line solution for creating the same string from RGB.
However, you can combine the method above with
the FromArgb method found in the System.Color structure to
achieve the one-line conversion:
string htmlString = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.FromArgb(85, 120, 50));
The FromArgb method used above is a specific overload that only
passes the red, green and blue values to the color object. It is
important to note that even if you set an alpha value (the level of
opacity in the color) lower than 255 on the color structure, the
alpha value is ignored when the ColorTranslator.ToHtml method
returns the hexadecimal code for the color object. So these two
lines of code produce the same hexadecimal result (#465a9b):
string htmlString = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.FromArgb(70, 90, 155));
string htmlString = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.FromArgb(125, 70, 90, 155));
These methods have been available in .Net at least since the 1.1
release; if you are like me and deal mostly with the System.Web and
System.Data namespaces on a daily basis, it is easy to overlook
some of the simple solutions provided by the other libraries in
.Net.