Tomero Indonesia
Tomero Indonesia

Reputation: 1695

VB.NET CONVERT BYTE NUMBER TO 8 BIT (256 COLORS) RGB VALUE

I read this link Converting 8 bit color into RGB value

Then I tried the VB.NET code like the following:

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

But when one pixel is selected, an error occurs:

Arithmetic operation resulted in an overflow.

How do I get a byte value of an image with 256 colors (8 bits), and then restore the (conversion) resulting byte value into the RGB value.

Thanks :)

Upvotes: 0

Views: 2783

Answers (1)

bastos.sergio
bastos.sergio

Reputation: 6764

Your ColorNumber has been declared as a Byte, which can only store values from 0 to 255... Change the code to this:

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

Also, since you're using .Net you can just get the color with this function:

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

Upvotes: 1

Related Questions