I want to get the image in the clipboard and convert its data into a base64 encoded string so that I can put that into a HTML img tag.
I've tried the following:
from PIL import ImageGrab
from base64 import encodestring
img = ImageGrab.grabclipboard()
imgStr = encodestring(img.fp.read())
Plus some other combinations, all of which give me incorrect representations of the image.
I'm struggling with the docs on this one; does anyone have an idea on how to accomplish this?
ImageGrab.grabclipboard()
returns an Image
object. You need to convert it to a known image format, like jpeg or png, then to encode the resulting string in base64 to be able to
use it within an HTML img tag:
import cStringIO
jpeg_image_buffer = cStringIO.StringIO()
image.save(jpeg_image_buffer, format="JPEG")
imgStr = base64.b64encode(jpeg_image_buffer.getvalue())
(answer has been edited to fix the typo).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With