How to get color of pixel in coordinates 123, 456 in screen?

Solution 1:

I found a way to do this using only built-in components:

do shell script "screencapture -R123,456,1,1 -t bmp $TMPDIR/test.bmp && \
                 xxd -p -l 3 -s 54 $TMPDIR/test.bmp | \
                 sed 's/\\(..\\)\\(..\\)\\(..\\)/\\3\\2\\1/'"

Output is the color in hex, for example, ffffff for white.

The screencapture command takes a 1x1 screenshot of the coordinates, and outputs it in the bmp format to a temporary location.

The xxd command reads 3 bytes from that file at offset 54. 54 is the length of the header in the generated bmp file, and the next 3 bytes are the color of the pixel.

The sed command swaps the first two characters of the output with the last two. This is because the bmp stores the colors in reverse of the normal order - BBGGRR. This command swaps the order to the normal RRGGBB.

Solution 2:

Possible, but only if you chain together multiple events:

  1. Take a screenshot do shell script "screencapture -l" & windowid & " ~/test.png"
  2. Crop around the specific pixel using ImageMagick

Output:

convert ~/test.png -crop 1x1+123+456 txt:-
# ImageMagick pixel enumeration: 1,1,255,rgba
0,0: (  0, 74,117,251)  #004A75FB  rgba(0,74,117,0.984314)

The idea is to crop around a specific pixel, then output it to the special txt: format, with an output file name of - which is of course standard output.

You can leave out the the -crop 1x1+X+Y business to just get a listing of all pixels. Also note that you image must have an alpha channel to see the alpha channel, otherwise it just won't get included.