如何将PIL Image.image对象转换为base64字符串?

69

我想尝试对一个Base64编码的图片进行旋转90度的操作,然后将其转换回Base64字符串。但不幸的是,我还没有成功实现这个想法。

目前为止,我已经做了以下工作:

image_string = StringIO(base64.b64decode(base64_string_here))
image = Image.open(image_string)
angle = 90
rotated_image = image.rotate( angle, expand=1 )

请帮忙教我如何将这个旋转的图像转换为base64字符串。

下面是旋转图像的dir()

['_Image__transformer', '__doc__', '__getattr__', '__init__', '__module__', '__repr__', '_copy', '_dump', '_expand', '_makeself', '_new', 'category', 'convert', 'copy', 'crop', 'draft', 'filter', 'format', 'format_description', 'fromstring', 'getbands', 'getbbox', 'getcolors', 'getdata', 'getextrema', 'getim', 'getpalette', 'getpixel', 'getprojection', 'histogram', 'im', 'info', 'load', 'mode', 'offset', 'palette', 'paste', 'point', 'putalpha', 'putdata', 'putpalette', 'putpixel', 'quantize', 'readonly', 'resize', 'rotate', 'save', 'seek', 'show', 'size', 'split', 'tell', 'thumbnail', 'tobitmap', 'tostring', 'transform', 'transpose', 'verify']

1个回答

173

Python 3

import base64
from io import BytesIO

buffered = BytesIO()
image.save(buffered, format="JPEG")
img_str = base64.b64encode(buffered.getvalue())

Python 2

import base64
import cStringIO

buffer = cStringIO.StringIO()
image.save(buffer, format="JPEG")
img_str = base64.b64encode(buffer.getvalue())

23
我想说,在Python3.4中,您应该编写from io import BytesIObuffer = BytesIO()。还要记住,buffer已经是一个现有的内置名称(也许使用buffered)。请查看细致的文档 - Paolo
1
@用户 这意味着图像具有阿尔法通道(在您的图像中称为透明度水平)。如果您可以安全地将其去除,可以在保存图像并将其转换为base64字符串之前将图像转换为RGB,如下行所示: image = image.convert("RGB") - Eugene V
10
如果有人想要向图像中写入内容,这段代码是必要的:img_base64 = bytes("data:image/jpeg;base64,", encoding='utf-8') + img_str - Johnny
4
抱歉,但无法正常工作:我得到的是类似于"b'iVBORw0KGgoAAAA...."这样的字节串...我想要的是规范的base64字符串,即以"=="结尾的那个... - Phate
2
@Phate 使用.decode("<format>")。例如:img_base64_str = img_base64.decode("utf-8") - Chris Hayes
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接