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 Overflow
🌐
PyPI
pypi.org › project › pyperclipimg
pyperclipimg · PyPI
import pyperclip as pci from PIL import Image pci.copy(Image.open('example.png')) # Copy by Image object. To paste the image (that is, get the image from the clipboard), call paste().
      » pip install pyperclipimg
    
Published   Dec 17, 2024
Version   0.2.0
Discussions

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
Copy image to clipboard
Hello! I have some question: Is it possible to copy png graph into windows clipboard without saving an image ? More on community.plotly.com
🌐 community.plotly.com
0
0
May 17, 2018
Copy to system clipboard
I’m working on a an app (my 2nd GUI app) that generates a hash value (AKA: checksum) based on a selected file. Right now, the hash value is displayed in a Text Widget, which is has the ‘state’ set to ‘disabled’, so that said value can’t be messed with. More on discuss.python.org
🌐 discuss.python.org
5
0
June 2, 2022
How to copy file to clipboard
https://python-forum.io/thread-24315.html 4th hit googling "python copy file to clipboard windows" More on reddit.com
🌐 r/learnpython
2
7
June 22, 2022
🌐
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 😇

🌐
Note.nkmk.me
note.nkmk.me › home › python › pillow
Get the image from the clipboard with Python, Pillow | note.nkmk.me
April 22, 2022 - ImageGrab.grabclipboard() returns the image copied on the clipboard. The returned Image object can be processed in Pillow. Here, the image is saved with save(). ... from PIL import ImageGrab, Image img = ImageGrab.grabclipboard() print(img) ...
🌐
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: ...
🌐
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 - Now that we have the canvas set up and the image loaded, we can proceed with implementing the copy functionality. We'll create a function called copy_image_to_clipboard() that will be triggered when a button is pressed.
🌐
DevDungeon
devdungeon.com › content › grab-image-clipboard-python-pillow
Grab Image from Clipboard in Python with Pillow | DevDungeon
October 28, 2018 - ... This example demonstrates how to pull an image from the clipboard. It will store it in memory and a Pillow image object. Copy an image to your clipboard with CTRL-C before running to ensure an image is actually in your clipboard.
🌐
Omz Software
omz-software.com › pythonista › docs › ios › clipboard.html
clipboard — Copy and paste — Python 3.6.1 documentation
February 19, 2020 - If there are multiple images in ... be used to get an image at a given index. If the index is >= the number of images in the clipboard, None is returned. clipboard.set_image(image, format='png', jpeg_quality=0.75)¶ · 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 ...
Find elsewhere
🌐
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 - output = BytesIO() image.convert('RGB').save(output, 'BMP') data = output.getvalue()[14:] output.close() clip.OpenClipboard() clip.EmptyClipboard() clip.SetClipboardData(win32con.CF_DIB, data) clip.CloseClipboard() It should be noted here that ...
Top answer
1 of 8
23

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.

h are part of the scrot's internal specifiers.

$w   image width
$h   image height

So the final file name will look something like 2018-06-17_02:52:19_1365x384.png.

2 of 8
9

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

🌐
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. If not implemented on your platform, the functions will raise NotImplementedError. ... Author: Jason R. Coombs ... Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
      » pip install jaraco.clipboard
    
Published   Jan 25, 2021
Version   3.1.0
🌐
GitHub
gist.github.com › a-nakanosora › 9493b14836fe054294ade772e1df8c68
Blender Script draft - Copy image to clipboard · GitHub
December 20, 2020 - install pip & install pillow through pip: $ cd blender/2.xx/python $ bin/python.exe get-pip.py $ Scripts/pip.exe $ Scripts/pip install pillow ... If copied image's colors had changed, check Blender > Scene > "Color Management" settings.
🌐
Plotly
community.plotly.com › dash python
Copy image to clipboard - Dash Python - Plotly Community Forum
May 17, 2018 - Hello! I have some question: Is it possible to copy png graph into windows clipboard without saving an image ?
🌐
PyPI
pypi.org › project › pyjpgclipboard
Client Challenge
JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Python GTK+ 3 Tutorial
python-gtk-3-tutorial.readthedocs.io › en › latest › clipboard.html
20. Clipboard — Python GTK+ 3 Tutorial 3.4 documentation
In most circumstances, the selection named CLIPBOARD is used for everyday copying and pasting. PRIMARY is another common selection which stores text selected by the user with the cursor. 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 =
🌐
GitHub
github.com › asweigart › pyperclipimg
GitHub - asweigart/pyperclipimg: Cross-platform copy() and paste() functions for images.
>>> import pyperclip as pci >>> from pathlib import Path >>> pci.copy(Path('example.png')) # Copy by Path object. >>> import pyperclip as pci >>> from PIL import Image >>> pci.copy(Image.open('example.png')) # Copy by Image object.
Starred by 7 users
Forked by 2 users
Languages   Python 100.0% | Python 100.0%
🌐
Python.org
discuss.python.org › python help
Copy to system clipboard - Python Help - Discussions on Python.org
June 2, 2022 - I’m working on a an app (my 2nd GUI app) that generates a hash value (AKA: checksum) based on a selected file. Right now, the hash value is displayed in a Text Widget, which is has the ‘state’ set to ‘disabled’, so that …
🌐
Reddit
reddit.com › r/learnpython › how to copy file to clipboard
r/learnpython on Reddit: How to copy file to clipboard
June 22, 2022 -

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?

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