Read Pixel Color
Posted: Thu Apr 18, 2019 8:20 am
How would I read the color of a pixel into my PB program? Ideally it would read the color of the pixel at the mouse pointer.
Thank you.
Thank you.
http://www.purebasic.com
https://www.purebasic.fr/english/
Code: Select all
CompilerSelect #PB_Compiler_OS
CompilerCase #PB_OS_MacOS
ImportC ""
CGBitmapContextCreate(*bdata, width, height, bitsPerComponent, bytesPerRow, cs, bitmapInfo)
CGColorSpaceCreateDeviceRGB()
CGColorSpaceRelease(cs)
CGContextRelease(c)
CGImageRelease(image)
EndImport
Procedure.l GetColorUnderMouse()
Protected.i image, csRGB, ctx
Protected c.l, x.d, y.d, one.d = 1
x = DesktopMouseX()
y = DesktopMouseY()
csRGB = CGColorSpaceCreateDeviceRGB()
ctx = CGBitmapContextCreate(@c, 1, 1, 8, 4, csRGB, 1)
CGColorSpaceRelease(csRGB)
!extern _CGContextDrawImage
!extern _CGWindowListCreateImage
!movsd xmm0, [p.v_x]
!movsd xmm1, [p.v_y]
!movsd xmm2, [p.v_one]
!sub rsp, 32
!movsd [rsp ], xmm0
!movsd [rsp + 8], xmm1
!movsd [rsp + 16], xmm2
!movsd [rsp + 24], xmm2
!mov rdi, 1
!xor rsi, rsi
!xor rdx, rdx
!call _CGWindowListCreateImage
!add rsp, 32
!mov [p.v_image], rax
!mov rdi, [p.v_ctx]
!mov rsi, rax
!pxor xmm0, xmm0
!movsd xmm2, [p.v_one]
!sub rsp, 32
!movupd [rsp], xmm0
!movsd [rsp + 16], xmm2
!movsd [rsp + 24], xmm2
!call _CGContextDrawImage
!add rsp, 32
CGImageRelease(image)
CGContextRelease(ctx)
ProcedureReturn c | $ff000000
EndProcedure
CompilerCase #PB_OS_Windows
Procedure.l GetColorUnderMouse()
Protected.i hdc, c.l
hdc = GetDC_(0)
c = GetPixel_(hdc, DesktopMouseX(), DesktopMouseY())
ReleaseDC_(0, hdc)
ProcedureReturn c | $ff000000
EndProcedure
CompilerCase #PB_OS_Linux
ImportC ""
gdk_pixbuf_get_from_window(window, x, y, width, height)
gdk_pixbuf_get_pixels(pixbuf)
EndImport
Procedure.l GetColorUnderMouse()
Protected.i pixbuf, *buf.Ascii, c.l
pixbuf = gdk_pixbuf_get_from_window(gdk_get_default_root_window_(), DesktopMouseX(), DesktopMouseY(), 1, 1)
*buf = gdk_pixbuf_get_pixels(pixbuf)
c = *buf\a : *buf + 1
c | *buf\a << 8 : *buf + 1
c | *buf\a << 16
g_object_unref_(pixbuf)
ProcedureReturn c | $ff000000
EndProcedure
CompilerEndSelect
Code: Select all
pixcol = GetColorUnderMouse()
r = Red(pixcol): g = Green(pixcol): b = Blue(pixcol)
Yes, the returned value is a normal color value so you can use Red(), Green() and Blue().chris319 wrote:Wilbert: how do I extract R, G and B from your Mac code?
I'm guessing it's something like:
Code: Select all
pixcol = GetColorUnderMouse() r = Red(pixcol): g = Green(pixcol): b = Blue(pixcol)