The Computer Oracle

How to copy a picture to clipboard from command line in linux?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles

--

Chapters
00:00 How To Copy A Picture To Clipboard From Command Line In Linux?
00:12 Answer 1 Score 1
00:37 Answer 2 Score 7
01:29 Accepted Answer Score 7
01:55 Thank you

--

Full question
https://superuser.com/questions/301851/h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#linux #clipboard #pictures

#avk47



ANSWER 1

Score 7


I believe the reason why Leo Alekseyev script does not work sometimes (on some systems) is explained in this answer to a similar question. Important part quoted here:

One oddity that is different from most other systems: if the program owning the selection (clipboard) goes away, so does the selection.

When i run Leo's script in python shell, it is working, as long as the shell is running. So i think the clipboard data is lost, when the script is terminated. The solution posted in the answer, is working for me:

#!/usr/bin/env python
import gtk 
import sys

count = 0
def handle_owner_change(clipboard, event):
    global count
    print 'clipboard.owner-change(%r, %r)' % (clipboard, event)
    count += 1
    if count > 1:
       sys.exit(0)

image = gtk.gdk.pixbuf_new_from_file(sys.argv[1])
clipboard = gtk.clipboard_get()
clipboard.connect('owner-change', handle_owner_change)
clipboard.set_image(image)
clipboard.store()
gtk.main()

Update from _Vi: For completeness, adding the clipboard->file script:

#!/usr/bin/python
import gtk, pygtk
pygtk.require('2.0')
import sys, os

clipboard = gtk.clipboard_get()
img = clipboard.wait_for_image()
img.save(sys.argv[1], "png", {})



ACCEPTED ANSWER

Score 7


As found here, the key to paste binary data to a file with xclip is to tell what Media Types you have on clipboard. For PNG you can:

xclip -selection clipboard -t image/png -o > "`date '+%Y-%m-%d_%T'`.png"

Or image/jpeg and .jpg for JPEG.

So now on my ~/Dropbox/.mybashrc I add an alias (clipboard2photo) to easly paste to image file (maybe someday we'll have it on Nautilus).




ANSWER 3

Score 1


The following python/pygtk script does the job:

#!/usr/bin/python
import gtk, pygtk
pygtk.require('2.0')
import sys, os

def copy_image(f):
    assert os.path.exists(f), "file does not exist"
    image = gtk.gdk.pixbuf_new_from_file(f)
    clipboard = gtk.clipboard_get()
    clipboard.set_image(image)
    clipboard.store()

copy_image(sys.argv[1]);

(Source: http://ubuntuforums.org/showthread.php?t=1689889)

To use this, sudo apt-get install python pygtk, paste the above code into a script, chmod +x to make executable, and you should be good to go.