How to covert System.Drawing.Color to a HTML/CSS color value

The System.Drawing.Color represenation of the color including the alpha color element:
alpha, red, green, blue.
The process is simple - convert the decimal color representation to a hexadecimal, then remove the alpha hexadecimal value from the string and concatenate to '#'.

Dim HTMLColor As String = Hex(color.ToArgb())
HTMLColor = "#" + HTMLColor.Substring(2)

where "color" is an instance of System.Drawing.Color

There is a difference between VB.NET and C# in getting the hexadecimal value as string. The C# fans can use the folloing code:

string HTMLColor = color.ToArgb().ToString("X8");
HTMLColor = "#" + HTMLColor.Substring(2);


The opposite process can be accomplished by ColorTranslator' services:
Dim color As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#e5e5e5")

No comments:

Post a Comment