I did copy the code and replace the StringIO with BytesIO and it worked! (with *.jpg and *.png files) Thank you so much!
from io import BytesIO
import win32clipboard
from PIL import Image
def send_to_clipboard(clip_type, data):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(clip_type, data)
win32clipboard.CloseClipboard()
filepath = 'Ico2.png'
image = Image.open(filepath)
output = BytesIO()
image.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
send_to_clipboard(win32clipboard.CF_DIB, data)
Answer from Luis Villamil on Stack OverflowI did copy the code and replace the StringIO with BytesIO and it worked! (with *.jpg and *.png files) Thank you so much!
from io import BytesIO
import win32clipboard
from PIL import Image
def send_to_clipboard(clip_type, data):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(clip_type, data)
win32clipboard.CloseClipboard()
filepath = 'Ico2.png'
image = Image.open(filepath)
output = BytesIO()
image.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
send_to_clipboard(win32clipboard.CF_DIB, data)
You don't want StringIO here. Images are raw binary data, and in Py3, str is purely for text; bytes and bytes-like objects (bytearray, contiguous memoryviews, mmaps) are for binary data. To replace Py2's StringIO.StringIO for binary data, you want to use io.BytesIO in Python 3, not io.StringIO.
» pip install pyperclipimg
Write image to Windows clipboard in python with PIL and win32clipboard? - Stack Overflow
Copy image to clipboard
Copy to system clipboard
How to add/get image data in the OS clipboard using Python? - Stack Overflow
Hi,
I am making a program that copies the an images from the downloads folder as soon as I download something from the internet. I am using watchdogs module for observing the folder but the problem is I don’t know how to copy an image to clipboard. There is no good solution on the internet for this problem. PLEASE HELP GUYS ! I Will award the best answer 😇
scrot + xclip
You can use scrot with xclip to take a screenshot and copy it to clipboard.
scrot '/tmp/%F_%T_
h.png' -e 'xclip -selection clipboard -target image/png -i $f'
It will capture whole of your screen and copy the image to clipboard. If you want to capture current window then use -u flag. For selection of particular area, you can add -s flag. See $ man scrot for more options.
It will store your screenshot in /tmp directory. You can change that directory wherever you want it to get stored. Files from /tmp directory usually gets deleted after each reboot. If you want to immediately remove the stored file, then do something like:
scrot -w '/tmp/%F_%T_
h.png' -e 'xclip -selection clipboard -target image/png -i $f && rm $f'
As I read in other comments, you need it for copying a screenshot to the clipboard. I hope this answers your question.
If you just need to copy an already existing image file to clipboard:
cat 2018-06-16-224938_670x730_scrot.png | xclip -selection clipboard -target image/png -i
You can set keyboard shortcuts/keybindings according to your current Desktop Environment/window manager.
Bonus
Explanation of /tmp/%F_%T_:h.png
It's being used as the file name. These are called format specifiers. They are of two type: starting with % or $.
%F Equivalent to %Y-%m-%d (the ISO 8601 date format). %T The time in 24-hour notation (%H:%M:%S).
%F_%T_ will print something like: 2018-06-17_02:52:19_ i.e. your current timestamp. You can customize the format as per your requirements. See $ man strftime for more help.
are part of the scrot's internal specifiers.h
$w image width $h image height
So the final file name will look something like 2018-06-17_02:52:19_1365x384.png.
First, install python, and pygtk
sudo apt-get install python pygtk
Now save the following script somewhere as imgclip.py (see https://stackoverflow.com/questions/3571855/pasting-image-to-clipboard-in-python-in-linux)
#! /usr/bin/python
import pygtk
pygtk.require('2.0')
import gtk
import os
import sys
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]);
To use it:
python /path/to/imgclip.py filename.png
Note: tested pasting in gimp and xournal. Note: this is for gnome desktop (hence gtk). I bet there's something similar for kde
» pip install jaraco.clipboard
from cStringIO import StringIO
import win32clipboard
from PIL import Image
def send_to_clipboard(clip_type, data):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(clip_type, data)
win32clipboard.CloseClipboard()
filepath = 'image.jpg'
image = Image.open(filepath)
output = StringIO()
image.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()
send_to_clipboard(win32clipboard.CF_DIB, data)
The file header off-set of BMP is 14 bytes. Well, BMP is also known as the device independent bitmap (DIB) file format, so you don't need to worried about the magic number 14.
FYI, it does need a windows clipboard API. Hence you can use BMP but can't use
image.convert("RGB").save(output, "PNG")
data = output.getvalue()[8:]
even you know the offset is 8 for PNG.
Question: How to add/get image data in the OS clipboard using Python?
I show only get:
This example is using the built-in Tkinter module to get image data from CLIPBOARD.
Tested only on Linux, but should be a cross-platform solution.

Note: The first
pasteof the shown 387x388 GIF, takes 4 seconds.
Core point: You have to use a MIME-Type, to requests a image.
.clipboard_get(type='image/png')
Verfied with, 'GIF', 'PNG' and 'JPEG', as source image data, using application, GIMP and PyCharm. With type='image/png' you allways get image data of type 'PNG' if the source app support this.
Reference:
clippboard_get(type=<string>)Retrieve data from the clipboard. Type specifies the form in which the data is to be returned and should be an atom name such as STRING or FILE_NAME. Type defaults on modern X11 systems to UTF8_STRING.
Data format:
0x89 0x50 0x4e 0x47 0xd 0xa 0x1a 0xa 0x0 0x0 0x0 0xd 0x49 0x48 0x44
The data is divided into fields separated by white space; each field is converted to its atom value, and the 32-bit atom value is transmitted instead of the atom name.
After removing the white space and casting with int(<field>, 0):
bytearray(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHD...')
<PIL.PngImagePlugin.PngImageFile image mode=P size=387x388 at 0xF555E20C>
Exception: If no selection at all or the source app does not provide 'image/png'.
TclError:CLIPBOARD selection doesn't exist or form "image/png" not defined
import tkinter as tk
from PIL import Image, ImageTk
import io
class App(tk.Tk):
def __init__(self):
super().__init__() # options=(tk.Menu,))
self.menubar = tk.Menu()
self.config(menu=self.menubar)
self.menubar.add_command(label='paste', command=self.on_paste)
self.label = tk.Label(self, text="CLIPBOARD image", font=("David", 18),
image='', compound='center')
self.label.grid(row=0, column=0, sticky='w')
def on_paste(self):
self.label.configure(image='')
self.update_idletasks()
try:
b = bytearray()
h = ''
for c in self.clipboard_get(type='image/png'):
if c == ' ':
try:
b.append(int(h, 0))
except Exception as e:
print('Exception:{}'.format(e))
h = ''
else:
h += c
except tk.TclError as e:
b = None
print('TclError:{}'.format(e))
finally:
if b is not None:
with Image.open(io.BytesIO(b)) as img:
print('{}'.format(img))
self.label.image = ImageTk.PhotoImage(img.resize((100, 100), Image.LANCZOS))
self.label.configure(image=self.label.image)
Tested with Python: 3.5 - 'TclVersion': 8.6 'TkVersion': 8.6
I don't think you could interact with the clipboard without external module.
Clipboard APIs are different from different Operating systems.
I suggest you to use the clipboard module.
https://pypi.python.org/pypi/clipboard/0.0.4
Hi!
I need help.
I wants to copy a file into the clipboard so that I can paste it using right click and paste.
I don't wants to copy content of the file but file itself. I wants to use right click or {CTRL + V} to paste file at desired location. I'm unable to find anything on google
Can any please help me?