Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell command to get color under mouse cursor (xorg)

Tags:

shell

xorg

I need to get the color in hex code of the pixel beneath my mouse cursor. There are plenty fancy GUI-tools to solve this task, but I need a simple command line way to get the color, so that I can use the solution in a shell script.

Possibly I could use ImageMagick to take a (one pixel?) screenshot and extract the color from it (I can fetch the position using xdotool)). Maybe there is a simpler solution.

Any suggestions?

like image 910
Christian Avatar asked Feb 28 '14 15:02

Christian


2 Answers

Not really satisfied with the other solution, I tried my ImageMagick idea. Works fine for me! (Depends on xclip, ImageMagick, xdotool, notify-send)

#!/bin/sh
# Get hex rgb color under mouse cursor, put it into clipboard and create a
# notification.

eval $(xdotool getmouselocation --shell)
IMAGE=`import -window root -depth 8 -crop 1x1+$X+$Y txt:-`
COLOR=`echo $IMAGE | grep -om1 '#\w\+'`
echo -n $COLOR | xclip -i -selection CLIPBOARD
notify-send "Color under mouse cursor: " $COLOR

EDIT:

Now using Gnome Shell, I have problems with the above solution (import won't take a screenshot of the visible windows, I don't know why. Hints are welcome). An alternative is to use a (fast) screenshot taker like scrot and use convert instead of import:

#!/bin/sh
# Get hex rgb color under mouse cursor, put it into clipboard and create a
# notification.

scrot --overwrite /tmp/copycolor.png
eval $(xdotool getmouselocation --shell)
IMAGE=`convert /tmp/copycolor.png -depth 8 -crop 1x1+$X+$Y txt:-`
COLOR=`echo $IMAGE | grep -om1 '#\w\+'`
echo -n $COLOR | xclip -i -selection CLIPBOARD
notify-send "Color under mouse cursor: " $COLOR

Update 2020: Newer versions of scrot require the "--overwrite" option to be set for this to work.

like image 164
Christian Avatar answered Sep 24 '22 03:09

Christian


Sure you can. But you need another linux package. If you're on Ubuntu just issue:

sudo apt-get install xdotool grabc

Then run grabc but background it

grabc &

Then perform a mouseclick using xdotool

xdotool click 1

The click will be captured by grabc's cursor and the background process will output the color.

But maybe it won't work from a script. For that purposes you might want to look at this topic on the Ubuntu forums.

Or if you don't mind, you can do it with python as described here.

like image 37
Zsolt Botykai Avatar answered Sep 22 '22 03:09

Zsolt Botykai