I would just use Pillow:
from PIL import ImageGrab
im = ImageGrab.grabclipboard()
im.save('somefile.png','PNG')
Answer from Gerrat on Stack OverflowI would just use Pillow:
from PIL import ImageGrab
im = ImageGrab.grabclipboard()
im.save('somefile.png','PNG')
You need to pass a parameter to GetClipboardData specifying the format of the data you're looking for. You can use EnumClipboardFormats to see the formats that are available - when I copy something in Explorer there are 15 formats available to me.
Edit 2: Here's the code to get a filename after you've copied a file in Explorer. The answer will be completely different if you've copied an image from within a program, a browser for example.
import win32clipboard
win32clipboard.OpenClipboard()
filename_format = win32clipboard.RegisterClipboardFormat('FileName')
if win32clipboard.IsClipboardFormatAvailable(filename_format):
input_filename = win32clipboard.GetClipboardData(filename_format)
win32clipboard.CloseClipboard()
Edit 3: From the comments it's clear you have an actual image in the clipboard, not the filename of an image file. You've stated that you can't use PIL, so:
import win32clipboard
win32clipboard.OpenClipboard()
if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_DIB):
data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB)
win32clipboard.CloseClipboard()
At this point you have a string (in Python 2) or bytes (in Python 3) that contains the image data. The only format you'll be able to save is .BMP, and you'll have to decode the BITMAPINFOHEADER to get the parameters for a BITMAPFILEHEADER that needs to be written to the front of the file.
» pip install pyperclipimg
How to copy an image to clipboard with python
python - Copy image to clipboard? - Stack Overflow
How to add/get image data in the OS clipboard using Python? - Stack Overflow
Write image to Windows clipboard in python with PIL and win32clipboard? - 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 😇
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)
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 jaraco.clipboard
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
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.