41

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!

EDIT

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:

#!/bin/bash
TMP=/tmp/screenshot.png
function screenshotfail {
  notify-send -u low -i image "Screenshot failed."
  exit
}
# 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"
artfulrobot
  • 8,753
  • Seems a duplicate of: https://unix.stackexchange.com/questions/30093/copy-image-from-command-line-to-clipboard – Champ Oct 12 '18 at 14:57
  • Feel free to post an answer post to your own question, so the community can upvote the answer, and so your answer doesn't get prioritised over other answers that the community may prefer – Flimm Feb 05 '24 at 17:36

1 Answers1

65

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

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