VB.NET CONVERT BYTE NUMBER到8位(256色)RGB值

时间:2013-08-08 13:28:25

标签: vb.net colors data-conversion 8-bit 256color

我已阅读此链接Converting 8 bit color into RGB value

然后我尝试了如下的VB.NET代码:

Private Sub picturebox1_MouseDown(ByVal sender As Object, _
                          ByVal e As System.Windows.Forms.MouseEventArgs) _
                          Handles picturebox1.MouseDown

    Dim bm As New Bitmap(picturebox1.Image)
    Dim Red As Byte = bm.GetPixel(e.X, e.Y).R
    Dim Green As Byte = bm.GetPixel(e.X, e.Y).G
    Dim Blue As Byte = bm.GetPixel(e.X, e.Y).B

    Dim ColorNumber As Byte = ((Red / 32) << 5) + ((Green / 32) << 2) + (Blue / 64)

    ' Show Byte Number of color
    MsgBox(ColorNumber)

    MsgBox(Red & ":" & Green & ":" & Blue)

    Red = (ColorNumber >> 5) * 32
    Green = ((ColorNumber >> 2) << 3) * 32
    Blue = (ColorNumber << 6) * 64

    MsgBox(Red & ":" & Green & ":" & Blue)


End Sub

但是当选择一个像素时,会发生错误:

  

算术运算导致溢出。

如何获取256色(8位)图像的字节值,然后将(转换)结果字节值恢复为RGB值。

谢谢:)

1 个答案:

答案 0 :(得分:1)

您的ColorNumber已声明为字节,只能存储0到255之间的值...将代码更改为:

Dim ColorNumber As Int32 = ((Red / 32) << 5) + ((Green / 32) << 2) + (Blue / 64)

此外,既然您正在使用.Net,您可以使用此功能获得颜色:

Dim color As Color = Color.FromRgb(Red, Green, Blue)