40

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"
2
  • Seems a duplicate of: unix.stackexchange.com/questions/30093/…
    – Champ
    Oct 12, 2018 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 5 at 17:36

1 Answer 1

63

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

xclip -selection clipboard -t image/png -i example.png
8
  • -t doesn't work on on my xclip version 0.12
    – Irfan
    Nov 7, 2016 at 5:59
  • @Power-Inside: Works for me with xclip 0.12 on 16.10 Nov 7, 2016 at 11:18
  • 3
    to get this to work on 17.10 I had to do this: xclip -selection clipboard -t image/png -o > example.png
    – Anake
    May 3, 2018 at 8:48
  • Works with xclip version 0.12 on my Ubuntu 16.04.5 LTS
    – Champ
    Oct 12, 2018 at 15:50
  • 1
    Works only for GTK environments like Gnome, not for Qt environments like KDE/plasma or LXQT.
    – noraj
    Jan 7, 2019 at 13:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .