使用 PIL 和 win32clipboard 将图像写入 python 中的 Windows 剪贴板?
我正在尝试打开图像文件并将图像复制到 Windows 剪贴板。有没有办法解决这个问题:
import win32clipboard
from PIL import Image
def send_to_clipboard(clip_type, data):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(clip_type, data)
win32clipboard.CloseClipboard()
clip_type = win32clipboard.CF_BITMAP
filepath = 'c:\\temp\\image.jpg'
im = Image.open(filepath)
data = im.tobitmap() # fails with valueerror: not a bitmap
# data = im.tostring() runs, but receiving programs can't read the results
send_to_clipboard(clip_type, data)
我可以安装 PythonMagick 等,但不想为一次性程序安装另一个库
I'm trying to open an image file and copy the image to the Windows clipboard. Is there a way to fix this:
import win32clipboard
from PIL import Image
def send_to_clipboard(clip_type, data):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(clip_type, data)
win32clipboard.CloseClipboard()
clip_type = win32clipboard.CF_BITMAP
filepath = 'c:\\temp\\image.jpg'
im = Image.open(filepath)
data = im.tobitmap() # fails with valueerror: not a bitmap
# data = im.tostring() runs, but receiving programs can't read the results
send_to_clipboard(clip_type, data)
I could install PythonMagick, etc., but would prefer not installing yet another library for a one-off program
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
BMP 的文件头偏移量为 14 个字节。嗯,BMP 也称为设备无关位图 (DIB) 文件格式,因此您无需担心幻数 14。
仅供参考,它确实需要 Windows 剪贴板 API。 无法使用。
因此,您可以使用 BMP,但即使您知道 PNG 的偏移量为 8,也
The file header off-set of BMP is 14 bytes. Well, BMP is also known as the device independent bitmap (DIB) file format, so you don't need to worried about the magic number 14.
FYI, it does need a windows clipboard API. Hence you can use BMP but can't use
even you know the offset is 8 for PNG.
这在Python 3.8中对我有用(在这里找到解决方案 )
这与 cgohike 的答案相同,但是:
更改为:
完整代码:
This worked for me in Python 3.8 (solution found here)
It's the same answer as the cgohike's but:
changed into:
Full code:
其他答案的附录,也可以将 PNG(可能还有其他格式)复制到剪贴板。我使用了以下内容:
此答案相关问题详细说明了某些程序对非标准剪贴板格式的支持“ PNG”,我在回答中使用了它。如果您要复制到的程序接受自定义剪贴板格式,这是一种替代方法。当然,您也可以一起定义许多标准和/或非标准剪贴板格式。
Addendum to the other answers, it's also possible to copy PNG (and probably other formats) to the clipboard. I've used the following:
This answer to a related question details support by some programs for the non-standard clipboard format "PNG", which I used in my answer. If the program you want to copy to accepts a custom clipboard format, this is an alternative. You can also of course define many standard and/or non-standard clipboard formats together.