【问题标题】:Write image to Windows clipboard in python with PIL and win32clipboard?使用 PIL 和 win32clipboard 在 python 中将图像写入 Windows 剪贴板?
【发布时间】:2011-08-13 12:35:26
【问题描述】:

我正在尝试打开一个图像文件并将该图像复制到 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 等,但不希望为一次性程序安装另一个库

【问题讨论】:

    标签: python python-imaging-library pywin32


    【解决方案1】:
    from cStringIO import StringIO
    import win32clipboard
    from PIL import Image
    
    def send_to_clipboard(clip_type, data):
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardData(clip_type, data)
        win32clipboard.CloseClipboard()
    
    filepath = 'image.jpg'
    image = Image.open(filepath)
    
    output = StringIO()
    image.convert("RGB").save(output, "BMP")
    data = output.getvalue()[14:]
    output.close()
    
    send_to_clipboard(win32clipboard.CF_DIB, data)
    

    【讨论】:

    • 为什么是幻数 14?它会在 Python 3 或 64 位 Python 上中断吗?非常感谢您提供非常有用的答案。
    • @MichaelPlatings 14 因为 BMP 文件有 14 字节的标头。无论 BMP 文件复制到 32 位还是 64 位系统,此标头都保留 14 个字节。在 Python 3 下,您需要将 StringIO 更改为 BytesIO。
    • 对于python 3,需要修改两行如下-from io import BytesIO ... output = BytesIO()
    • @DamianYerrick PNG 的价值是什么?
    • @CoolCloud 查看 yfyang 的回答。 PNG 的标头是 8 个字节,但 Windows 剪贴板不使用 PNG。
    【解决方案2】:

    BMP 的文件头偏移量为 14 字节。嗯,BMP 也被称为设备无关位图 (DIB) 文件格式,所以你不必担心幻数 14。

    仅供参考,它确实需要一个 Windows 剪贴板 API。因此你可以使用 BMP 但不能使用

    image.convert("RGB").save(output, "PNG")
    data = output.getvalue()[8:]
    

    即使你知道 PNG 的偏移量是 8。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-29
      • 2020-04-16
      • 2018-03-16
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多