Read pixel colors of an image

落爺英雄遲暮 提交于 2019-12-04 23:59:50

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/16528319/read-pixel-colors-of-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!