Created
May 18, 2022 08:25
-
-
Save BibMartin/ddd5380f95a92679b71477536fbea1a7 to your computer and use it in GitHub Desktop.
Wanna copy images and paste it in a notebook
This file contains 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
# !pip install clipboard | |
# !pip install Pillow | |
import clipboard | |
from PIL import ImageGrab, Image | |
import base64 | |
def clipboard_to_image(): | |
"""Reads image in the clipboard and outputs a PIL.Image""" | |
image = ImageGrab.grabclipboard() | |
if ((isinstance(image, list) | |
and (len(image) == 1) | |
and isinstance(image[0], str) | |
and os.path.exists(image[0]) | |
)): | |
image = Image.open(image[0]) | |
if isinstance(image, Image.Image): | |
return image | |
return None | |
def clipboard_to_markdown_image(alt_text="image"): | |
"""Reads image in the clipboard and write it in the clipboard, as a markdown string.""" | |
image = clipboard_to_image() | |
assert image is not None, 'No valid image in the clipboard' | |
clipboard.copy( | |
'![drawing](data:image/png;base64,' | |
+ base64.b64encode(image._repr_png_()).decode() | |
+ ")") | |
print('Copied to cliboard. Now paste the result in a markdown cell.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment