Convert the Color structure to HTML and vice versa





8
Date Submitted Thu. Sep. 21st, 2006 6:47 AM
Revision 1 of 1
Scripter Pio
Tags System.Drawing.Color | VB.NET
Comments 3 comments
Have you ever tried to use Color.Blue.ToString and gotten undesired results?
Or have you ever tried to save a color to an INI and not be able to reproduce it the next time around?

The methods below will help you in your conquest of converting the Color structure to HTML (#FF0000) and back to a Color structure again.

  Public Function Color2Html(ByVal clr As Color) As String
    Return "#" & clr.ToArgb().ToString("x").Substring(2)
  End Function
 

    Dim myHTML As String = Color2Html(Color.Blue)
    'myHTML now contains #0000FF
 

  Public Function HexToColor(ByVal hexString As String) As Color

    Try
      Dim r, g, b As Integer

      hexString = hexString.Replace("#", Nothing)
      If Not hexString.Length = 6 Then
        Return Color.Black
      End If

      r = HexToInt(hexString.Substring(0, 2))
      g = HexToInt(hexString.Substring(2, 2))
      b = HexToInt(hexString.Substring(4, 2))

      Return Color.FromArgb(255, r, g, b)
    Catch ex As Exception
      Debug.WriteLine(ex.ToString)

      Return Color.Black
    End Try


  End Function

  'Keep it Global
  Private Function HexToInt(ByVal hexString As String) As Int32
    Return Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber, Nothing)
  End Function
 

    Dim myColor As Color = HexToColor("#0000FF")
    'myColor is now Color.Blue
 


Enjoy,
-Pio

Allen Gammel

p-soft.org
Allen / Pio
email: intolerance@gmail.com

Comments

Comments Great
Fri. Jul. 6th, 2007 7:34 AM    Beginner babakzawari
Comments Even Better...
Wed. Sep. 27th, 2006 10:25 AM    Newbie RobK410
  Comments Well
Thu. Sep. 28th, 2006 7:35 PM    Scripter Pio

Voting