devxlogo

Getting a pixel color

Getting a pixel color

The Point method returns the color value of a given pixel, but is rather slow because it has to convert its argument from twips (or whatever ScaleMode is currently active) to pixels, and also because its argument are treated as Single quantities, and must therefore converted. When you have to retrieve the color value of many pixels you should use the GetPixel API function instead. Here is its declaration:

Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long, ByVal x As Long, _    ByVal y As Long) As Long

The following code example counts the number of red pixels on the active form:

' assumes that form's ScaleMode' is set to 3 - PixelsDim x As Long, y As LongDim h As Long, count As Long' cache form's hDC propertyh = Me.hdcFor y = 0 To ScaleHeight - 1    For x = 0 To ScaleWidth - 1        If GetPixel(h, x, y) = vbRed Then            count = count + 1        End If    NextNext

It is about three times faster than the equivalent code that uses the Point method. Note that we can have this speed increment also because we cache the hDC property into a variable.

See also  5 Tips for Working With an Onsite Interpreter
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist