Read pixel colors of an image

28,513

Try the solution posted on this site here : http://sim0n.wordpress.com/2009/03/27/vba-q-how-to-get-pixel-colour/

I had to change a ByRef to a ByVal but apart from that it works well. Insert a picture using Insert > Picture and assign a macro to the on click event . I've just made it set the colour of cell A1 to the colour you click on, but I'm sure you get the idea.

#If VBA7 Then
    Private Declare PtrSafe Function GetPixel Lib "gdi32" (ByVal hdc As LongPtr, ByVal x As Long, ByVal y As Long) As Long
    Private Declare PtrSafe Function GetCursorPos Lib "user32" (ByRef lpPoint As POINT) As LongPtr
    Private Declare PtrSafe Function GetWindowDC Lib "user32" (ByVal hwnd As LongPtr) As LongPtr
#Else
    Private Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long, ByVal x As Long,     ByVal y As Long) As Long
    Private Declare Function GetCursorPos Lib "user32" (ByRef lpPoint As POINT) As Long
    Private Declare Function GetWindowDC Lib "user32" (ByVal hwnd As Long) As Long
#End If
Private Type POINT
    x As Long
    y As Long
End Type

Sub Picture1_Click()
    Dim pLocation As POINT
    Dim lColour As Long

    Dim lDC As Variant
    lDC = GetWindowDC(0)
    Call GetCursorPos(pLocation)
    lColour = GetPixel(lDC, pLocation.x, pLocation.y)
    Range("a1").Interior.Color = lColour
End Sub

To use it, place a picture in a worksheet, right click on the image and assign this macro to it.

Share:
28,513
KM Hs
Author by

KM Hs

Updated on October 12, 2020

Comments

  • KM Hs
    KM Hs over 3 years

    In VBA, how can I read the color value of each pixel of in an image?

    I found this solution in VB 6.0 but it doesn't apply directly in VBA.