PIL剪贴板图像到Base64字符串

时间:2014-08-15 10:20:41

标签: python encoding base64 python-imaging-library clipboard

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

我尝试过以下方法:

from PIL import ImageGrab
from base64 import encodestring
img = ImageGrab.grabclipboard()
imgStr = encodestring(img.fp.read())

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

我在这个问题上与文档挣扎;有没有人知道如何做到这一点?

1 个答案:

答案 0 :(得分: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())

(已修改答案以解决错字)。