Do pyperclip3 or pasteboard support paste of PNG on macOS

104 views Asked by At

I am trying to figure out how to paste a PNG graphic from the clipboard into a Python script on macOS. I have looked into using the pyperclip, pyperclip3, and pasteboard modules. I cannot get any of these to work. I am able to paste text from the clipboard, but not PNG.

The project description for pyperclip explicitly states that it is for copy/paste of text data.

The overview for pyperclip3 states that it has cross-platform support for both text and binary data. It also states that it is using pasteboard as the backend for MacOS.

There is a caveat in the description of the get_contents function in pasteboard that states:

type - The format to get. Defaults to pasteboard.String, which corresponds to NSPasteboardTypeString. See the pasteboard module members for other options such as HTML fragment, RTF, PDF, PNG, and TIFF. Not all formats of NSPasteboardType are implemented.

It does not, however, give any indication of which formats may or may not actually be implemented.

Here is the complete script from my attempts to make pasteboard work:

import pasteboard
pb = pasteboard.Pasteboard()
x = pb.get_contents(type=pasteboard.PNG)
print(type(x))
print(x)

If I drop the type argument from get_contents and there is text in the clipboard, this works as expected. If I keep the type=pasteboard.PNG argument and there is PNG data in the clipboard, the output shows that the type of x in NoneType

And this is the complete script from my attempts to make pyperclip3 work:

import pyperclip3
x = pyperclip3.paste()
print(type(x))
print(x)

In this case it doesn't matter if I have text or PNG data in the clipboard, the type of x is bytes. For text, the content of x is as expected. For PNG data, the content of x is the empty byte string.

Is what I'm trying to do even possible? Or am I wasting my time trying to figure out how to make pasting of PNG data into a python script work?

2

There are 2 answers

0
MikeMayer67 On BEST ANSWER

Turns out that the type attribute that is needed by pasteboard is public.tiff, not Pasteboard.PNG. With that, I was able to capture PNG data from the clipboard into a PIL Image via pb.get_contents()

3
just a guy On

PIL.Imagegrab.grabclipboard() also exists to grab an image from the clipboard!