Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hex color string to RGB color

I want to convert hex color to RGB color.

I used the following code:

Me.BackColor = RGB("#000000")

But then it throws the following exception:

Argument not specified for parameter 'Green' of 'Public Function RGB(Red As Integer, Green As Integer, Blue As Integer) As Integer'

What is the right way to do it?

like image 798
Nh123 Avatar asked Nov 13 '12 06:11

Nh123


People also ask

Are hex codes for RGB?

A HEX color is expressed as a six-digit combination of numbers and letters defined by its mix of red, green and blue (RGB). Basically, a HEX color code is shorthand for its RGB values with a little conversion gymnastics in between.

What color is R 255 G 0 B 255?

RGB(255, 255, 255) is white.


2 Answers

By ColorTranslator:

ColorTranslator.FromHtml("#003399") 

Other Ways:

Public Function ConvertToRbg(ByVal HexColor As String) As Color
    Dim Red As String
    Dim Green As String
    Dim Blue As String
    HexColor = Replace(HexColor, "#", "")
    Red = Val("&H" & Mid(HexColor, 1, 2))
    Green = Val("&H" & Mid(HexColor, 3, 2))
    Blue = Val("&H" & Mid(HexColor, 5, 2))
    Return Color.FromArgb(Red, Green, Blue)
End Function

or:

Public Shared Function HexToColor(ByVal hexColor As String) As Color
    If hexColor.IndexOf("#"c) <> -1 Then
        hexColor = hexColor.Replace("#", "")
    End If
    Dim red As Integer = 0
    Dim green As Integer = 0
    Dim blue As Integer = 0
    If hexColor.Length = 6 Then
        red = Integer.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier)
        green = Integer.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier)
        blue = Integer.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier)
    ElseIf hexColor.Length = 3 Then
        red = Integer.Parse(hexColor(0).ToString() + hexColor(0).ToString(), NumberStyles.AllowHexSpecifier)
        green = Integer.Parse(hexColor(1).ToString() + hexColor(1).ToString(), NumberStyles.AllowHexSpecifier)
        blue = Integer.Parse(hexColor(2).ToString() + hexColor(2).ToString(), NumberStyles.AllowHexSpecifier)
    End If
    Return Color.FromArgb(red, green, blue)
End Function

or:

    Dim c As String = "#ffffff"
    c = Replace(c, "#", "")
    c = "&H" & c
    ColorTranslator.FromOle(c)

or:

Public Function hexToRbgNew(ByVal Hex As String) As Color
    Hex = Replace(Hex, "#", "")
    Dim red As String = "&H" & Hex.Substring(0, 2)
    Hex = Replace(Hex, red, "", , 1)
    Dim green As String = "&H" & Hex.Substring(0, 2)
    Hex = Replace(Hex, green, "", , 1)
    Dim blue As String = "&H" & Hex.Substring(0, 2)
    Hex = Replace(Hex, blue, "", , 1)
    Return Color.FromArgb(red, green, blue)
End Function
like image 107
famf Avatar answered Sep 19 '22 12:09

famf


This works for me: (vb.Net)

cell.BackColor = Drawing.Color.FromArgb(&H3399FF)
like image 45
Eduardo Avatar answered Sep 18 '22 12:09

Eduardo