将RGB值转换为整数

时间:2014-04-25 12:21:01

标签: vb.net

我正在使用g.CopyFromScreen(screenpoint,Point.Empty,Bmp2.Size)制作带有颜色滴管工具的应用程序(滴管工具当前工作),一旦我有了我想要的滴管值将RBG值转换为单个整数。

我转换的格式为此格式 颜色[A = 255,R = 240,G = 240,B = 240] 它需要有四个不同的整数

我的代码给了我奇怪的结果,我现在迷失了

我的代码:

    Dim text1Conv As String

    text1Conv = TextBox1.Text
    Dim myChars() As Char = text1Conv.ToCharArray()

For Each ch As Char In myChars
        If Char.IsDigit(ch) And Not ch = " " And Not ch = "," And Not count > 2 Then
            color1Conv = color1Conv + ch
            TextBox2.Text = TextBox2.Text + color1Conv 'test result
            count = count + 1
        ElseIf Char.IsDigit(ch) And Not ch = " " And Not ch = "," And count < 2 And Not count > 5 Then
            color2Conv = color2Conv + ch
            TextBox2.Text = TextBox2.Text + color2Conv 'test result
            count = count + 1
        ElseIf Char.IsDigit(ch) And Not ch = " " And Not ch = "," And count < 5 And Not count > 8 Then
            color3Conv = color3Conv + ch
            TextBox2.Text = TextBox2.Text + color3Conv 'test result
            count = count + 1
        ElseIf Char.IsDigit(ch) And Not ch = " " And Not ch = "," And count < 8 And Not count > 11 Then
            color4Conv = color4Conv + ch
            TextBox2.Text = TextBox2.Text + color4Conv 'test result
            count = count + 1
        End If

    Next

结果:225 255 118 112 122 结果:225 255 116 772 721

可能很容易,但我看不到它

2 个答案:

答案 0 :(得分:1)

使用正则表达式: 我使用“[A = 255,R = 241,G = 24,B = 2]”作为测试字符串并将其拆分为四个整数。

Dim a as Integer, r as Integer, g as Integer, b as Integer
Dim s as String = "[A=255, R=241, G=24, B=2]"
Dim mc as MatchCollection = System.Text.RegularExpressions.Regex.Matches( s, "(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+", RegexOptions.None )  
Integer.TryParse( mc(0).Groups(1).Value, a )
Integer.TryParse( mc(0).Groups(2).Value, r )
Integer.TryParse( mc(0).Groups(3).Value, g )
Integer.TryParse( mc(0).Groups(4).Value, b )

注意:数字为1,2或任意长度的数字都没有问题。

答案 1 :(得分:0)

您可以使用正则表达式:

Imports System.Text.RegularExpressions

Dim input As String = "Color [A=255, R=240, G=240, B=240]"
Dim re As New Regex("Color \[A=(\d+), R=(\d+), G=(\d+), B=(\d+)\]")
Dim m As Match = re.Match(input)
Dim integer1 As Integer = Convert.ToInt32(m.Groups(1).Value) '255
Dim integer2 As Integer = Convert.ToInt32(m.Groups(2).Value) '240
Dim integer3 As Integer = Convert.ToInt32(m.Groups(3).Value) '240
Dim integer4 As Integer = Convert.ToInt32(m.Groups(4).Value) '240