繁体   English   中英

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

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

我正在尝试将在 PIL 中创建的图像复制到 macOS 剪贴板。

我找到了两种方法:

  1. 使用粘贴板 (pypi.org/project/pasteboard),但那个似乎不适用于 Python 3.10(我在尝试安装它时遇到轮子错误)。

  2. 另一种方法来自此处( 使用 python 将图像复制到 MacOS 剪贴板)并使用以下代码:

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

我尝试使用第二种方法,但我无法让它与在 Pillow 中创建的图像一起使用。 例如:

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

在原始帖子中“???” 是一个 image.jpg,那么我怎么能在那里插入 PIL 数据呢? 我尝试了一些变体,但一直出现相同的错误:

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)

这会将图像复制为数据 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)))

然后您就可以将其粘贴到浏览器中,但可能不会粘贴到文件管理器中

如果这没有回答您的问题,那么您可能必须找到一个支持 mac 剪贴板的库。

暂无
暂无

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

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