Copy PIL/PILLOW Image to Windows Clipboard

前端 未结 2 1455
一向
一向 2020-12-12 01:13

I\'ve seen this question and i followed every step, changing the code to satisfy my requirements, that are Python3, Pillow, and ctypes. The less libraries, the better.

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 01:57

    Whew. Apparently the win32clipboard library does simplify some things when compared to ctypes. Your attempt to simply replace one with the other is far from correct.

    So I booted up my Windows virtual machine, installed Pillow and rewrote your program, learning from two other answers:

    import io
    
    import ctypes
    msvcrt = ctypes.cdll.msvcrt
    kernel32 = ctypes.windll.kernel32
    user32 = ctypes.windll.user32
    
    from PIL import ImageGrab
    
    img = ImageGrab.grab()
    output = io.BytesIO()
    img.convert('RGB').save(output, 'BMP')
    data = output.getvalue()[14:]
    output.close()
    
    CF_DIB = 8
    GMEM_MOVEABLE = 0x0002
    
    global_mem = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(data))
    global_data = kernel32.GlobalLock(global_mem)
    msvcrt.memcpy(ctypes.c_char_p(global_data), data, len(data))
    kernel32.GlobalUnlock(global_mem)
    user32.OpenClipboard(None)
    user32.EmptyClipboard()
    user32.SetClipboardData(CF_DIB, global_mem)
    user32.CloseClipboard()
    

提交回复
热议问题