Last active
May 24, 2025 15:29
-
-
Save kenny-kvibe/e8b7dbe422ca945426e22aac353cfbc0 to your computer and use it in GitHub Desktop.
Copy "image" or "text" to Windows system clipboard
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import io | |
| import win32clipboard | |
| import PIL.Image as Image | |
| def copy_to_clipboard(data: str | Image.Image) -> None: | |
| """ Copy `data` as "image/bmp" or "text/plain" to system clipboard """ | |
| if isinstance(data, Image.Image): | |
| fmt = win32clipboard.CF_DIB | |
| with io.BytesIO() as stream: | |
| data.convert('RGB').save(stream, 'BMP') | |
| value = stream.getvalue()[14:] | |
| else: | |
| fmt = win32clipboard.CF_UNICODETEXT | |
| value = str(data) | |
| win32clipboard.OpenClipboard() | |
| win32clipboard.EmptyClipboard() | |
| win32clipboard.SetClipboardData(fmt, value) | |
| win32clipboard.CloseClipboard() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment