Get hex color from Drawing.Color

Peter Volz 1,295 Reputation points
2023-05-23T21:38:07.1366667+00:00

Hello

Dim Col As Color = Color.FromArgb(Red * 255, Green * 255, Blue * 255)

Now I have Col, how should I convert it to hex color to insert in html pages?

It is expected to be in a format like: #0b7ed9

Col.ToArgb.ToString("X6") and .ToArgb.ToString("X") will return something like FFA142CC which is not valid for html pages.

Any tips?

Thanks :)

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,604 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,657 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Dewayne Basnett 1,361 Reputation points
    2023-05-24T13:14:18.94+00:00

    There is a built-in method just for this.

            Dim someColor As Color = Color.LightCoral
            Dim htmlColor As String = System.Drawing.ColorTranslator.ToHtml(Color.FromArgb(someColor.ToArgb()))
    
    1 person found this answer helpful.
    0 comments No comments

  2. Jiachen Li-MSFT 28,781 Reputation points Microsoft Vendor
    2023-05-24T01:29:37+00:00

    Hi @Peter Volz ,

    You can get the hex data for each color channel individually and combine it.

    You can refer to the following code.

        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim Col As Color = Color.FromArgb(255, 255, 255)
            Dim hexColor As String = ColorToHex(Col)
            Console.WriteLine(hexColor) ' Output: #FF0000
        End Su
    
        Public Function ColorToHex(color As Color) As String
            Return "#" & color.R.ToString("X2") & color.G.ToString("X2") & color.B.ToString("X2")
        End Function
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments