简体   繁体   English

使用 Python 将 PIL 图像复制到 macOS 剪贴板

[英]copy an PIL image to the macOS clipboard with Python

I am trying to copy a image created in PIL to the macOS clipboard.我正在尝试将在 PIL 中创建的图像复制到 macOS 剪贴板。

I found 2 ways:我找到了两种方法:

  1. Using Pasteboard (pypi.org/project/pasteboard) but that one does not seem to work with Python 3.10 (I get a wheels error when trying to install it).使用粘贴板 (pypi.org/project/pasteboard),但那个似乎不适用于 Python 3.10(我在尝试安装它时遇到轮子错误)。

  2. The other way is from here ( Copy an image to MacOS clipboard using python ) and uses the following code:另一种方法来自此处( 使用 python 将图像复制到 MacOS 剪贴板)并使用以下代码:

     import subprocess subprocess.run(["osascript", "-e", 'set the clipboard to (read (POSIX file 'image.jpg') as JPEG picture)'])

I tried playing around with this second approach but I cannot get it to work with an image created in Pillow.我尝试使用第二种方法,但我无法让它与在 Pillow 中创建的图像一起使用。 For example:例如:

import subprocess
from PIL import Image 

image = Image.open('img.png') 
subprocess.run(["osascript", "-e", 'set the clipboard to (read (POSIX file '???') as JPEG picture)'])

In the original post the '???'在原始帖子中“???” was an image.jpg, so how could I insert the PIL data in there?是一个 image.jpg,那么我怎么能在那里插入 PIL 数据呢? I tried some variations but kept on getting the same error:我尝试了一些变体,但一直出现相同的错误:

CFURLGetFSRef was passed an URL which has no scheme (the URL will not work with other CFURL routines)
22:67: 2023-01-12 13:53:42.227 osascript[1361:27923] CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme
execution error: Can’t make file ":image" into type file. (-1700)

This will copy the image as a data URL :这会将图像复制为数据 URL

import base64
from io import BytesIO
from PIL import Image 
image = Image.open('img.png') 
buffered = BytesIO()
image.save(buffered, format="PNG")
base64_enc = base64.b64encode(buffered.getvalue())
print("data:image/png;base64,"+"".join(map(chr,base64_enc)))

which you then will be able to paste in your browser, and probably not in file manager though然后您就可以将其粘贴到浏览器中,但可能不会粘贴到文件管理器中

if this didn't answer your question then you probably have to find a library that supports mac clipboard.如果这没有回答您的问题,那么您可能必须找到一个支持 mac 剪贴板的库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM