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
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
pywin32 - How do I read a jpg or png from the windows clipboard in python and vice versa? - Stack Overflow
I have an image (jpg, png, etc.) in the windows clipboard. I'd like to save it to a file. win32clipboard would seem to be the answer, but every example I can find deals with text. copy an image t... More on stackoverflow.com
🌐 stackoverflow.com
Is it possible to use Python to copy an image to the Windows clipboard without losing its transparency in the process? - Stack Overflow
I've spent the past few hours trying to find a definitive answer, but all I have come across is a bunch of inconclusive, or conflicting, or seemingly-incompatible-with-python information. output =... More on stackoverflow.com
🌐 stackoverflow.com
February 1, 2019
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
🌐
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
🌐
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) ...
🌐
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 😇

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.

🌐
Stack Overflow
stackoverflow.com › questions › 54467484 › is-it-possible-to-use-python-to-copy-an-image-to-the-windows-clipboard-without-l
Is it possible to use Python to copy an image to the Windows clipboard without losing its transparency in the process? - Stack Overflow
February 1, 2019 - I've spent the past few hours trying to find a definitive answer, but all I have come across is a bunch of inconclusive, or conflicting, or seemingly-incompatible-with-python information. output = io.BytesIO() image.save(output, "BMP") data = output.getvalue()[14:] output.close() win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data) win32clipboard.CloseClipboard() The above method I found lets me paste the image into the application Discord for instance, but causes the transparency to be lost as I expected.
🌐
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 ...
Find elsewhere
🌐
CopyProgramming
copyprogramming.com › howto › copy-image-to-clipboard
Copy image to clipboard? - Python 3 x
May 23, 2023 - Instead of Py2's StringIO.StringIO for binary data, use io.BytesIO in Python 3 and avoid using io.StringIO . bytearray , contiguous memoryview s, and mmap s are specifically created for handling binary data. ... After replacing StringIO with BytesIO, I was able to successfully run the code with both *.jpg and *.png files. Your help is greatly appreciated! 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)
🌐
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.
🌐
DevDungeon
devdungeon.com › content › grab-image-clipboard-python-pillow
Grab Image from Clipboard in Python with Pillow | DevDungeon
October 28, 2018 - For example, if you used your Grab or Snipping Tool to capture a section of your screen, but you haven't actually saved it yet, you can CTRL-C to copy the image to your clipboard.
🌐
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.
🌐
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
🌐
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: ...
🌐
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 ...
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_$wx$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_$wx$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_$wx$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.

$wx$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

🌐
GitHub
gist.github.com › RayPS › 5f8c31de2a4ded2f0e947996c30ab1fe
Converting image format in clipboard - macOS Python (Copied as PNG, Paste as JPG) · GitHub
Converting image format in clipboard - macOS Python (Copied as PNG, Paste as JPG) - convert-clipboard-image.py
🌐
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 =