Command Line – How to Copy an Image to Clipboard from a File

clipboardcommand line

I'd like to write a script to take an image file, scale it 50% and put it on the clipboard so it can be pasted easily. The bit I'm stuck on is how to place an image on the clipboard.

I know of xclip, but AFAICS that only deals with text. Is it possible to have an image on the clipboard without the application that generated it sitting around? – Sorry I'm not sure of the internals of how the clipboard works!


Thanks to Florian's answer below I was able to achieve what I wanted, which was to take a screenshot and automatically scale it to a max of 600px wide (e.g. for pasting into an email). The further problem I faced was that Thunderbird won't accept image/png from the clipboard. I got round this by converting it to text/html with a data url. Here's my code in case anyone finds it useful:

function screenshotfail {
  notify-send -u low -i image "Screenshot failed."
# Take screenshot
gnome-screenshot -a -b -p -f "$TMP" || screenshotfail
# Ensure it's max 600px wide
mogrify -resize '>600x' "$TMP" || screenshotfail
# optimise the png if optipng is installed.
which optipng >/dev/null && optipng "$TMP"

# Copy to clipboard.
# This is what does not work for Thunderbird:
#   xclip -selection clipboard -t image/png <"$TMP" || screenshotfail
# But this does:
echo "<img src='data:image/png;base64,"$(base64 -w0 "$TMP")"' />" | \
  xclip -selection clipboard -t text/html || screenshotfail

# Remove the temp file.
rm -f "$TMP"

# Notify user.
notify-send -u low -i image "600px screenshot copied to clipboard"

Best Answer

Use the -t option to specify the content type, like

xclip -selection clipboard -t image/png -i example.png