Image copy from Clipboard

The win32clipboard module provides method of getting content from clipboard. But, when it comes to image content, bytes data are returned and are hard to convert to image type(involving Bitmap Header and ‘PIL.Image.frombytes() ‘ requires size though is unknown).

However, PIL module offers function can grab image from clipboard.

# from PIL/ImageGrab.py
...
def grabclipboard():
    if sys.platform == "darwin":
        fh, filepath = tempfile.mkstemp('.jpg')
        os.close(fh)
        commands = [
            "set theFile to (open for access POSIX file \""+filepath+"\" with write permission)",
            "try",
                "write (the clipboard as JPEG picture) to theFile",
            "end try",
            "close access theFile"
        ]
        script = ["osascript"]
        for command in commands:
            script += ["-e", command]
        subprocess.call(script)

        im = None
        if os.stat(filepath).st_size != 0:
            im = Image.open(filepath)
            im.load()
        os.unlink(filepath)
        return im
    else:
        data = Image.core.grabclipboard()
        if isinstance(data, bytes):
            from . import BmpImagePlugin
            import io
            return BmpImagePlugin.DibImageFile(io.BytesIO(data))
        return data

So, ‘BmImagePlugin.DibImageFile()’ is exactly what we need.

import win32clipboard as w
from PIL import Image, BmpImagePlugin
import io
#
w.OpenClipboard()
if w.IsClipboardFormatAvailable(w.CF_DIB):
    c = w.GetClipboardData(w.CF_DIB)
    im = BmpImagePlugin.DibImageFile(io.BytesIO(c))
    im.show() # or other operations
w.CloseClipboard()

发表评论

电子邮件地址不会被公开。