如何使用Python将EMF文件复制到Windows中的剪贴板?

问题描述 投票:0回答:1

我正在尝试使用 Python3.12 上的

win32clipboard
模块将 EMF(增强型图元文件)文件直接复制到 Windows 剪贴板。但我面临一个问题,
SetClipboardData
抛出“无效句柄”错误。这是我正在尝试的代码:

import win32clipboard

def copy_emf_to_clipboard(emf_file_path):
    with open(emf_file_path, 'rb') as f:
        emf_data = f.read()

    try:
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardData(win32clipboard.CF_ENHMETAFILE, emf_data)
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        win32clipboard.CloseClipboard()

copy_emf_to_clipboard('input.emf')

执行此代码时,出现以下错误:

An error occurred: (6, 'SetClipboardData', 'The handle is invalid.')

有人可以解释为什么会发生此错误以及如何正确地将 EMF 数据复制到剪贴板吗?处理 EMF 文件时是否需要遵循任何特定步骤或剪贴板格式?

python windows clipboard .emf
1个回答
0
投票

当您使用

f.read()
读取文件时,您正在获取该文件,但
SetClipboardData
函数需要增强型图元文件的句柄。修改后的代码使用 Pillow 库读取图像,该库可以处理 EMF 格式,然后将图像数据保存到剪贴板。

from PIL import Image
import win32clipboard
import io

def copy_emf_to_clipboard(emf_file_path):
    # disable the limit
    Image.MAX_IMAGE_PIXELS = None
    
    with Image.open(emf_file_path) as img:
        output = io.BytesIO() # Create a binary stream in memory
        img.save(output, format='BMP') # Save the image to the stream in BMP format
        data = output.getvalue()[14:] # Get the image data from the stream and skip BMP header
        output.close()

    
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
    win32clipboard.CloseClipboard()

copy_emf_to_clipboard('input.emf')
© www.soinside.com 2019 - 2024. All rights reserved.