I would just use Pillow:

from PIL import ImageGrab
im = ImageGrab.grabclipboard()
im.save('somefile.png','PNG')
Answer from Gerrat on Stack Overflow
Top answer
1 of 4
39

I would just use Pillow:

from PIL import ImageGrab
im = ImageGrab.grabclipboard()
im.save('somefile.png','PNG')
2 of 4
7

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.

🌐
PyPI
pypi.org › project › pyperclipimg
pyperclipimg · PyPI
Cross-platform copy() and paste() Python functions for images. ... Python copy() and paste() clipboard functions for images on Windows, macOS, and Linux.
      » pip install pyperclipimg
    
Published   Dec 17, 2024
Version   0.2.0
Discussions

How to copy an image to clipboard with python
What OS are we talking about? Windows, Linux, Mac? More on reddit.com
🌐 r/learnpython
9
2
April 17, 2021
python - Copy image to clipboard? - Stack Overflow
First of all, the question on SO copy image to clipboard in python leads to answer Write image to Windows clipboard in python with PIL and win32clipboard?, which was only good for Python 2.x. -- I ... More on stackoverflow.com
🌐 stackoverflow.com
How to add/get image data in the OS clipboard using Python? - Stack Overflow
I have some Python code that edits image files and would like to know how to add image data to the Operating System clipboard and get it from there. When searching for a cross-platform solution to More on stackoverflow.com
🌐 stackoverflow.com
Write image to Windows clipboard in python with PIL and win32clipboard? - Stack Overflow
I'm trying to open an image file and copy the image to the Windows clipboard. Is there a way to fix this: import win32clipboard from PIL import Image def send_to_clipboard(clip_type, data): More on stackoverflow.com
🌐 stackoverflow.com
July 8, 2014
🌐
Note.nkmk.me
note.nkmk.me › home › python › pillow
Get the image from the clipboard with Python, Pillow | note.nkmk.me
April 22, 2022 - from PIL import ImageGrab, Image img = ImageGrab.grabclipboard() print(img) # <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=200x71 at 0x105E68700> print(isinstance(img, Image.Image)) # True print(img.size) # (200, 71) print(img.mode) # RGB img.save('data/temp/clipboard_image.jpg')
🌐
Reddit
reddit.com › r/learnpython › how to copy an image to clipboard with python
r/learnpython on Reddit: How to copy an image to clipboard with python
April 17, 2021 -

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 😇

🌐
GeeksforGeeks
geeksforgeeks.org › python › pyhton-pil-imagegrab-grabclipboard-method
Python PIL | ImageGrab.grabclipboard() method - GeeksforGeeks
July 29, 2019 - Syntax: PIL.ImageGrab.grabclipboard() Parameters: no arguments Returns: On Windows, an image, a list of filenames, or None if the clipboard does not contain image data or filenames.
🌐
DevDungeon
devdungeon.com › content › grab-image-clipboard-python-pillow
Grab Image from Clipboard in Python with Pillow | DevDungeon
October 28, 2018 - For text only clipboard operations, check out pyperclip - Cross-platform text only Python 2&3 module. Install the pillow package using pip in your command line shell. ... This example demonstrates how to pull an image from the clipboard. It will store it in memory and a Pillow image object.
🌐
Quora
quora.com › Can-we-get-an-image-from-local-storage-to-clipboard-with-Python-or-a-little-program-How-can-I-use-https-xpshort-com-nircmd-with-this
Can we get an image from local storage to clipboard with Python or a little program? How can I use https://xpshort.com/nircmd with this? - Quora
Answer: Yes, you can get an image from local storage to clipboard using the [code ]pyperclip[/code] library in Python. Here is an example of how to do this: [code]pythonCopy codeimport pyperclip with open("path/to/image.png", "rb") as image_file: ...
Find elsewhere
🌐
PyPI
pypi.org › project › jaraco.clipboard
jaraco.clipboard · PyPI
from jaraco import clipboard clipboard.copy('some text') clipboard.paste() == 'some text' Other functions include copy/paste html and image.
      » pip install jaraco.clipboard
    
Published   Jan 25, 2021
Version   3.1.0
🌐
Omz Software
omz-software.com › pythonista › docs › ios › clipboard.html
clipboard — Copy and paste — Python 3.6.1 documentation
February 19, 2020 - Store a given PIL Image in the clipboard. The format parameter can be ‘png’ or ‘jpeg’. jpeg_quality is ignored if format is ‘png’, otherwise, it should be a float between 0.0 and 1.0. © Copyright 1990-2020, Python Software Foundation. The Python Software Foundation is a non-profit ...
🌐
Python GTK+ 3 Tutorial
python-gtk-3-tutorial.readthedocs.io › en › latest › clipboard.html
20. Clipboard — Python GTK+ 3 Tutorial 3.4 documentation
1import gi 2 3gi.require_version("Gtk", "3.0") 4from gi.repository import Gtk, Gdk 5 6 7class ClipboardWindow(Gtk.Window): 8 def __init__(self): 9 super().__init__(title="Clipboard Example") 10 11 grid = Gtk.Grid() 12 13 self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) 14 self.entry = Gtk.Entry() 15 self.image = Gtk.Image.new_from_icon_name("process-stop", Gtk.IconSize.MENU) 16 17 button_copy_text = Gtk.Button(label="Copy Text") 18 button_paste_text = Gtk.Button(label="Paste Text") 19 button_copy_image = Gtk.Button(label="Copy Image") 20 button_paste_image = Gtk.Button(label="Paste
🌐
Python Programming
pythonprogramming.altervista.org › grab-an-image-from-the-screen-with-python-v-2
How to Capture a snippet image from the screen to the clipboard with Python (v.2) – python programming
# grabscreen.py import pyscreenshot as ImageGrab import os from pynput.mouse import Listener import sys import tkinter as tk from PIL import Image from io import BytesIO import win32clipboard ''' Derives from my script grab (use this to show text in a pic and transform in audio) ''' def send_to_clipboard(clip_type, data): win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(clip_type, data) win32clipboard.CloseClipboard() def grab(x, y, w, h): im = ImageGrab.grab(bbox=(x, y, w, h)) im.save('im.png') image = Image.open("im.png") output = BytesIO() image
🌐
YouTube
youtube.com › codethemall
Get Image From Clipboard In Python. - YouTube
In this video, we will get the image from the clipboard to python using pillow library.Song: Jarico - Island (Vlog No Copyright Music)Music promoted by Vlog ...
Published   May 8, 2021
Views   895
🌐
Clay-Technology World
clay-atlas.com › home › use python to copy pictures to the clipboard
Use Python to copy pictures to the clipboard - Clay-Technology World
October 30, 2020 - May be you can refer: Recording with Python —— Provided a sample code · If you are using pywin32 in the first time, you need to use the following command to install: ... And we can start to coding. # -*- coding: utf-8 -*- import win32clipboard as clip import win32con from io import BytesIO from PIL import ImageGrab · First, import the module we need. ImageGrab() is a function to take the screenshot in Pillow. And win32clipboard can make us to copy the image to our clipboard...
Top answer
1 of 5
1

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 paste of 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

2 of 5
0

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

🌐
GitHub
github.com › siriak › clipboard-image-saver
GitHub - siriak/clipboard-image-saver: Clipboard Image Auto Saver is a Python script which monitors the clipboard and automatically saves images from there
Clipboard Image Auto Saver is a Python script which monitors the clipboard and automatically saves images from there - siriak/clipboard-image-saver
Author   siriak
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-copy-a-picture-from-tkinter-canvas-to-clipboard
How to copy a picture from Tkinter canvas to clipboard?
December 5, 2023 - That's it! You have now implemented the functionality to copy an image from a Tkinter canvas to the clipboard. When the "Copy Image" button is clicked, the image will be converted to a PNG format and copied to the clipboard.
🌐
Python Forum
python-forum.io › thread-29933.html
Problem posting image to clipboard - Python Forum
I am running Windows 10 Version 10.0.18363 Build 18363. Python 3.8.5 Apache 2.4.41 I found an example of how to copy an image to windows clipboard. If I run the program at cmd.exe level, it works and I'm able to post the copied image from the clipbo...