Skip to content

Instantly share code, notes, and snippets.

@BibMartin
Created May 18, 2022 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BibMartin/ddd5380f95a92679b71477536fbea1a7 to your computer and use it in GitHub Desktop.
Save BibMartin/ddd5380f95a92679b71477536fbea1a7 to your computer and use it in GitHub Desktop.
Wanna copy images and paste it in a notebook
# !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