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

时间:2015-08-05 07:43:35

标签: python python-imaging-library

我试图以90度角旋转它来操纵base64编码图像。在这个操作之后,我想将它转换回base64字符串。但遗憾的是无法实现这一目标。

这是我到目前为止所做的:

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

Kindy帮我了解如何将rotate_image转换为base64字符串。

这里是rotate_image的dir()

  

[' _Image__transformer',' __ doc __',' __ getattr __',' __ init __',   ' __模块__',' __ repr __',' _copy',' _dump',' _expand',' _makeself& #39 ;,   ' _new',' category',' convert',' copy',' crop',' draft& #39;,' filter',   '格式',' format_description',' fromstring',' getbands',' getbbox',   ' getcolors',' getdata',' getextrema',' getim',' getpalette',   ' getpixel',' getprojection',' histogram',' im',' info',' load& #39 ;,   '模式','偏移','调色板','粘贴','点',' putalpha& #39;,' putdata',   ' putpalette',' putpixel',' quantze',' readonly',' resize',' rotate& #39 ;,   '保存','寻找','显示','尺寸','拆分','告诉& #39;,' thumbnail',   ' tobitmap',' tostring','转换','转置','验证']

1 个答案:

答案 0 :(得分:68)

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