How do I read a jpg or png from the windows clipboard in python and vice versa?

后端 未结 4 382
慢半拍i
慢半拍i 2020-12-08 03:25

I have an image (jpg, png, etc.) in the windows clipboard. I\'d like to save it to a file. win32clipboard would seem to be the answer, but every example I can find deals wi

4条回答
  •  一个人的身影
    2020-12-08 03:44

    You need to pass a parameter to GetClipboardData specifying the format of the data you're looking for. You can use EnumClipboardFormats to see the formats that are available - when I copy something in Explorer there are 15 formats available to me.

    Edit 2: Here's the code to get a filename after you've copied a file in Explorer. The answer will be completely different if you've copied an image from within a program, a browser for example.

    import win32clipboard
    win32clipboard.OpenClipboard()
    filename_format = win32clipboard.RegisterClipboardFormat('FileName')
    if win32clipboard.IsClipboardFormatAvailable(filename_format):
        input_filename = win32clipboard.GetClipboardData(filename_format)
    win32clipboard.CloseClipboard()
    

    Edit 3: From the comments it's clear you have an actual image in the clipboard, not the filename of an image file. You've stated that you can't use PIL, so:

    import win32clipboard
    win32clipboard.OpenClipboard()
    if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_DIB):
        data = win32clipboard.GetClipboardData(win32clipboard.CF_DIB)
    win32clipboard.CloseClipboard()
    

    At this point you have a string (in Python 2) or bytes (in Python 3) that contains the image data. The only format you'll be able to save is .BMP, and you'll have to decode the BITMAPINFOHEADER to get the parameters for a BITMAPFILEHEADER that needs to be written to the front of the file.

提交回复
热议问题