Reading images from the clipboard with =xclip=

I discovered how to read data other than text from xclip.

tl;dr

If you're short on time, here's the xclip command to get an image's data from the clipboard, in PNG file format:

xclip -selection clipboard -o -target image/png

image/png is one possible format, but if you can't export to PNG, you can type the following to figure out to which formats you can export the image:

xclip -selection clipboard -o -target TARGETS

The full story

Today, I needed to copy an image from Firefox into a file, but I didn't want to have to go through the Save As dialog; I wanted to use a single command in the terminal, since it'd be faster.

I use an X11-based window manager (Awesome) so I use xclip to copy things to the clipboard. I figured that there must be a way to read image data from the clipboard using xclip, and it turns out that there is!

xclip primer

xclip is a program used to interface with the X11 clipboard. You can use it to pipe things to the clipboard, which makes it really useful for a sort of manual IPC.

xclip also enables you to read from the clipboard.

xclip flags

Here are the flags that are relevant for our use case:

  • -selection clipboard: The data we're accessing is that from the clipboard, so we set -selection to clipboard. To quote page 12 of the ICCCM (which governs how inter-client communication works in X11):

    The selection named by the atom CLIPBOARD is used to hold data that is being transferred between clients, that is, data that usually is being cut and then pasted or copied and then pasted.

  • -o: We want to read from the clipboard to stdout.
  • -target <FORMAT>: This is the important part. A target in X11 IPC specifies the format in which the data should be returned.

<FORMAT>

To see which values <FORMAT> can be, copy your data to the clipboard, and run our xclip command with the special value TARGETS as the <FORMAT>.

xclip -selection clipboard -o -target TARGETS

You'll get a list of formats to which the data can be serialized. For example, when I choose Copy Image on an image in Firefox, running the xclip command yields the following:

TIMESTAMP TARGETS MULTIPLE SAVETARGETS text/html text/mozhtmlinfo text/mozhtmlcontext image/png image/bmp image/x-bmp image/x-MS-bmp image/x-icon image/x-ico image/x-win-bitmap image/vnd.microsoft.icon application/ico image/ico image/icon text/ico

From there, you can get the image data in any of the image/<x> formats. Since it's a Firefox image, I can also get the HTML of the <img> element if I use text/html as -target's argument.

To get the image data as PNG, and write the data to a file (called copied_img.png in this example), I can do the following:

xclip -selection clipboard -o -target image/png > copied_img.png