Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL Clipboard Image to Base64 string

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?

like image 778
Griffin Avatar asked Aug 15 '14 10:08

Griffin


1 Answers

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).

like image 168
mguijarr Avatar answered Oct 11 '22 01:10

mguijarr