View Cart | My Account
Imaging Hardware   Search site for:
PRODUCTS
 By:
R & D
Cards Accepted
 

Tutorial

How to read RGB values for each pixel from an Image in Visual Basic

by Guthrie Cooper
The problem with Visual Basic is that when you use the Picture.Point method to read the pixel value, it reports back the information as a LONG data type. The documentation for VB doesn't show how to read the Red, Green, and Blue values. This tutorial shows how to read the LONG data type and convert it to its respective R, G, and B values.
By using the Picture.MouseMove event, the X and Y coordinates respective to the top left corner are reported back as x and y variables. Using these x and y values and placing them into the Picture.Point method, reports back the LONG value data type. This data type has to be converted. Remember, that the minimum for any value for Red, Green, or Blue is 0 (0 HEX) and the maximum is 255 (FF in HEX). Don't worry about remembering your Hexadecimal math, because the below conversion algorithm does this for you. Out pops your r, g, b variables that represent separate Red, Green, and Blue values. Remember that when working with true Black and White images, Red = Green = Blue for each pixel. This saves considerable processing power when you want your application to run in real-time. Just to see the pixel directly underneath your mouse, I use a Shape from the toolbar to change to the color reported. (Helps in debugging) Happy Programming!
(Drag open a Picture Box onto your form, go to the properties and load in a picture. Cut and Paste the code into your CODE for the Form1)
Private Sub Picture1_MouseMove(Button As Integer, Shift As Integer, x As Single, y As Single)

Text1.Text = x
Text2.Text = y
Text3.Text = Picture1.Point(x, y)

r = Picture1.Point(x, y) And &HFF ' only right 2 bytes
g = (Picture1.Point(x, y) \ &H100&) And &HFF ' only middle 2 bytes
b = Picture1.Point(x, y) \ &H10000 ' only "left" 2 bytes

Text4.Text = r
Text5.Text = g
Text6.Text = b
Shape1.BackColor = Picture1.Point(x, y)

End Sub
Did you like this article or would you like to see another on a related topic? Please let us know.