C# .NET: Convert System.Drawing.Color to HTML color

29. June 2006

Here is a small example of how to convert a System.Drawing.Color to the HTML color format (Hex value or HTML color name value) and back.

System.Drawing.Color c = System.Drawing.ColorTranslator.FromHtml("#F5F7F8");
String strHtmlColor = System.Drawing.ColorTranslator.ToHtml(c);

 

General ,



Comments

7/31/2006 4:58:00 AM #
System.Drawing.Color c = System.Drawing.ColorTranslator.FromHtml("#F5F7F8");
String strHtmlColor = System.Drawing.ColorTranslator.ToHtml

thanks for the tip
Shriaknth
Shriaknth
8/23/2006 7:41:00 PM #
This piece of code is very good. Thanks it was very helpful.
Paul Diston
Paul Diston
11/5/2006 7:23:00 PM #
If you wish to use the above code on the Compact Framework you can using the OpenNETCF.Drawing assembly which has an implementation of the color translator. Thank you for your help.
D
D
12/6/2006 11:03:00 PM #
Aahh, eventually...works like a bomb
DW
DW
2/26/2007 3:01:00 AM #
In case you wanted to get the Hex value (#FF12200) of a color and not the html name of the color (ie. Color.Black returns "Black"), then you'll need to do the following.

From the AGRB value of the Color
dim s as String = Hex(Color.ToArgb)
'This gives you a string with the hex values of the Alpha, Red, Green, and Blue.  You can strip off the first two characters of the string to get just the RGB
s = s.Substring(2)

'Or you can get each of the hex values for the red, green, and blue

s = Hex(Color.R) & Hex(Color.G) & Hex(Color.B)

'And of course, if you need the pound sign, you can add it to the front of the string
s = "#" & s
Comments are closed