Get the image from the clipboard with Python, Pillow

Posted: | Tags: Python, Pillow, Image Processing

In Python, you can get the image from the clipboard with the ImageGrab.grabclipboard() function in Pillow(PIL). As of version 9.1.0 (April 2022), it is available only for Windows and macOS.

Note that ImageGrab also has the ImageGrab.grab() function that takes screenshots, although not mentioned in this article.

You can also work with the clipboard with pyperclip.

how to use ImageGrab.grabclipboard()

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)
# <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')

If any non-image, such as text, is copied on the clipboard, ImageGrab.grabclipboard() returns None.

img = ImageGrab.grabclipboard()
print(img)
# None

Related Categories

Related Articles