I wanted a way to grab a screenshot of a section of my screen on my Linux desktop. Running scrot and then cropping down two monitors worth of picture in GIMP is the kind of thing you do exactly once before you look for a better way. Now I don't want anything too much better. Otherwise I'd just tell you to install Gnome Screenshot or some other such tool and there wouldn't be anything more for me to talk about. The fun is in hacking it together myself after all.
So I'm going to say I don't want to install a special program just for this. I'm going to see what I have lying around.
ImageMagick is one of those sprawling tools that can do well nigh anything, and that includes screenshotting. It does this with the non-obviously named
import command. It's default behavior is conveniently close to what we want:
$ import $filename prompts you to select a region of the screen with your mouse, and writes that image to a file. But I want something even more casual, something I can just paste into Discord.
Step one is to switch from writing the image to a file to sending it to standard out. This is done in the usual way by providing a
- as the filename. Indicating the image format1 is done by preceding the filename with the format and a colon. So now we have
$ import png:-
Step two is to pipe this into the clipboard. I had
xclip a clipboard manager for X11 installed already for copying and pasting from Vim. There are others, consult their respective manuals. It needs two pieces of information: the type of data I'm putting in there, and which clipboard to put it in.
The final result is a tidy one liner:
import png:- | xclip -t image/png -selection clipboard
Now I can shove that into screenshot.sh and forget the details of it. I then bound that to `Print`, the print screen key.2 Note that import will block until you make the selection so you should arrange for the script to run in the background.