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
pci.paste().show() # (Also displays the clipboard's image on the screen.)
      » pip install pyperclipimg
    
Published   Dec 17, 2024
Version   0.2.0
Discussions

python - Copy image to clipboard? - Stack Overflow
Now open some app like work and ... copied pasted on the app. # 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, ... More on stackoverflow.com
🌐 stackoverflow.com
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
How to copy a image from clipboard in Python? - Stack Overflow
Any help would be great, the idea ... from clipboard to a variable and use the savescreenshot method to save it in a folder. Any help would be great. ... from PIL import ImageGrab, Image im= ImageGrab.grabclipboard() if isinstance(im, Image.Image): im.save('tmp.jpg') ... Reproducible with Pilllow 2.8.0, 2.8.1, 2.8.2. Not reproducible with Pillow 2.6.0, 2.7.0 https://github.com/python-pillow/Pi... More on stackoverflow.com
🌐 stackoverflow.com
May 28, 2017
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
🌐
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 ...
🌐
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')
🌐
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 after OpenClipboard(), emptyClipboard() should be used to empty the clipboard.
🌐
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. Or, if you right click an image in a web browser and choose "Copy Image". As always, refer to the Check out the Python Pillow package documentation for the most complete reference.
Find elsewhere
🌐
GitHub
gist.github.com › orschiro › 8b9a1ddadb696c2b4587
Python script that saves an image from clipboard to a file. · GitHub
January 18, 2019 - Python script that saves an image from clipboard to a file. - Image Clipboard Filer.md
🌐
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 =
🌐
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
Copy and Paste Text to the Clipboard with pyperclip in Python | note.nkmk.me
January 30, 2024 - Convert a string to a number (int, float) in Python · i = int(pyperclip.paste()) print(i) # 100 print(type(i)) # <class 'int'> ... If an image is copied to the clipboard, pyperclip.paste() returns an empty string (''). Images from the clipboard can be obtained using Pillow.
🌐
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
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

🌐
PyPI
pypi.org › project › jaraco.clipboard
jaraco.clipboard · PyPI
The only clipboard library for Python that supports text on all three major platforms plus HTML on MacOS and HTML and images on Windows. Similar to pyperclip and clipboard and xerox except attempts to support more formats than just text. This library is just a thin wrapper around the best platform implementations: ... jaraco.clipboard supplies several functions in the clipboard module. The most common are the copy and paste functions: from jaraco import clipboard clipboard.copy('some text') clipboard.paste() == 'some text'
      » pip install jaraco.clipboard
    
Published   Jan 25, 2021
Version   3.1.0
🌐
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
🌐
CopyProgramming
copyprogramming.com › howto › copy-image-to-clipboard
Copy image to clipboard? - Python 3 x
May 23, 2023 - Code sampleimport pyperclippyperclip.copy('The text to be copied to the clipboard.')spam = pyperclip.paste()Feedback ... Avoid using StringIO here as it is not suitable for handling images. In Python 3, str is only meant for text, while bytes and bytes are designed for binary data.
🌐
Medium
medium.com › @shimo164 › move-image-files-in-paste-image-with-python-9c3ac4a76710
Move image files in Paste Image with Python | by shimo | Medium
December 16, 2021 - Paste on VSCode markdown file (Ctrl+Alt+v). A link is pasted in markdown file like ![](img/YYYY-MM-DD-hh-mm-ss.png) The image file is saved in the folder as YYYY-MM-DD-hh-mm-ss.png.
Top answer
1 of 8
40

xclip

xclip (man page) is on official repos of major distros (pasteimg it isn't and last update was on 2011).

For me the quickest way is using terminal, going to the desired folder (maybe using Z) and then just run clipboard2photo, which is an alias I created to the following command:

xclip -selection clipboard -t image/png -o > "$(date +%Y-%m-%d_%T).png"  # Use "Screenshot from $(date "+%Y-%m-%d %H-%M-%S").png" if you like GNOME filename format.

To save in JPEG format instead of PNG using imagemagick:

f="$(date '+%Y-%m-%d_%T').png" && xclip -selection clipboard -t image/png -o > "$f" && mogrify -format jpg "$f" && rm "$f" && unset "f"

With something on clipboard you can get all possible targets with: xclip -selection clipboard -o -t TARGETS.

GNOME Files/Nautilus

GNOME v44 let you paste directly from clipboard to Files/Nautilus.

GNOME Shell shortcuts

On GNOME Shell (Ubuntu 17.10+) we have built in shortcuts to save screenshots directly to ~/Pictures:

Hints to remember them:

  • Ctrl → to clipboard (else to ~/Pictures)
  • Alt → Current window
  • Shift → Area/Surface

I usually disable "Print" to avoid generating garbage on ~/Pictures if I miss F12 (which I use a lot with Guake) and accidentally press it.


Tip 1: Put your aliases on ~/sync_folder/.mybashrc (or maybe better .myprofile; where sync_folder might be Nextcloud or any other service) and then include this file from .bashrc.

[ -r ~/sync_folder/.mybashrc ] && source ~/sync_folder/.mybashrc

This way you will have them on all your current and future devices. Of course, you can also have a ~/.dotfiles with a git repo.

Tip 2: In the same way, you can: thisOutputMarkdown | pandoc -s -f markdown -t html | xclip -selection clipboard -t text/html to get formatted HTML to clipboard.
If you have the Markdown text on clipboard replace thisOutputMarkdown with xsel -b.

Wayland

It seems there is some work to be done about xclip on Wayland (echo $XDG_SESSION_TYPE). Please help developers on this issue. Meanwhile, maybe wl-paste (from wl-clipboard) might work:

wl-paste -t image/png > "$(date +%Y-%m-%d_%T).png"
2 of 8
9

I just threw together a quick python script that will paste a clipboard image to a file.

It's very basic but it does the job but could be easily extended.

PasteImg