PIL剪贴板图像到Base64字符串

Gri*_*fin 5 python clipboard base64 encoding python-imaging-library

我想在剪贴板中获取图像并将其数据转换为base64编码的字符串,以便我可以将其放入HTML img标记中.

我尝试过以下方法:

from PIL import ImageGrab
from base64 import encodestring
img = ImageGrab.grabclipboard()
imgStr = encodestring(img.fp.read())
Run Code Online (Sandbox Code Playgroud)

加上一些其他组合,所有这些组合都给我错误的图像表示.

我正在努力研究这个问题; 有没有人知道如何实现这一目标?

mgu*_*arr 10

ImageGrab.grabclipboard()返回一个Image对象.您需要将其转换为已知的图像格式,如jpeg或png,然后在base64中对结果字符串进行编码,以便能够在HTML img标记中使用它:

import cStringIO

jpeg_image_buffer = cStringIO.StringIO()
image.save(jpeg_image_buffer, format="JPEG")
imgStr = base64.b64encode(jpeg_image_buffer.getvalue())
Run Code Online (Sandbox Code Playgroud)

(答案已被编辑以修复拼写错误).