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 :)

Developer technologies VB
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Dewayne Basnett 1,381 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 34,221 Reputation points Microsoft External Staff
    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.