since 1997 a place for my stuff, and if it helps you then so much the better

 
...
...

Color to HEX


It's not a huge deal anymore to use Hex values for colors in web pages, since Netscape3+ and IE both handle basically the same set of user-friendly color text values, but sometimes we need to feel like getting geeky helps cover the bases.

As with most things on the smithvoice.com sitelett, we found that we were typing this out by memory just often enough to make it tedious yet not often enough that our fingers could do it while we were watching TV. So we put it here for our future cut & pasting, and if it helps you too then so much the better.

  Public Class rcsColorUtil
   'The FromName will return a
   'Color with an rgb value of 0 if 
   'the name you provide does not match any
   'predefined names.  
   'so you don't have to check the IsNamedColor 
   'property for safety.  However, if you do want to check you
   'have to iterate through a color array which is relatively intensive
   Public Shared Function ColorToHex(ByVal Value As Color) As String
     Return InternalColorToHex(Value)
   End Function
     
   Public Shared Function ColorToHex(ByVal Value As String) As String
     Return InternalColorToHex(Color.FromName(Value))
   End Function
   
   Private Shared Function InternalColorToHex(ByVal Value As Color) As String
     Dim hr, hb, hg, fr, fg, fb As String
     hr = Hex(Value.R)
     If Len(hr) = 1 Then
        fr = "0" & hr
     Else
        fr = hr
     End If
     hg = Hex(Value.G)
     If Len(hg) = 1 Then
        fg = "0" & hg
     Else
        fg = hg
     End If
     hb = Hex(Value.B)
     If Len(hb) = 1 Then
        fb = "0" & hb
     Else
        fb = hb
     End If
     Return "#" & fr & fg & fb
   End Function
  End Class


Pass in a Color or a KnownColor string and the correct overloaded function will pass off to the internal worker function. Because the entry functions are defined as Shared you don't have to instantiate an rcsColorUtil object to do the do. The following will suffice:

  MsgBox(rcsColorUtil.ColorToHex("PaleGoldenrod"))
  
  'or...
  
  Dim c As Color = Color.SeaGreen
  MsgBox(rcsColorUtil.ColorToHex(c))

As the comment says, there's no need to do a check of [Value].IsNamedColor because passing anything, including Nothing will not throw an exception. If you pass junk to IsNamedColor then the result will still be True and the values of the R, G and B will all be zero.

Personally we wish an exception would be raised for garbage input, making it a bit more logically consistant, but such is life in .Net-land :)

Hope it helps!

Robert Smith
Kirkland, WA

 

added to smithvoice August 2004


...
...

"In theory, theory and practice are the same. In practice, they are not." -Albert Einstein