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

标签 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 )

请帮我把这个 rotate_image 转换成 base64 字符串。

这是rotated_image的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']

最佳答案

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

关于python - 如何将 PIL Image.image 对象转换为 base64 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31826335/

相关文章:

python - 在 Python 上显示来自 Matlab mat 文件的图像

python - 如何使用 Python 更改 .dbf 文件及其关联的 .mdx 文件?

python - 彩色图像的直方图均衡化 Python

python - 当分离 < 1 px 时在 python 中使用 PIL 检测图像形状边缘的算法

python - 如何合并100张图像以获得大图像?

python - 线性模型文本分类中的特征重要性,StandardScaler(with_mean=False) 是或否

python - iPython/Jupyter Notebook 和 Pandas,如何在 for 循环中绘制多个图?

python - 用(0,0,255)蓝色覆盖最接近蓝色的像素

python - 加载目录中的每个内部文件夹并保存

Python 图像库,ImageFont IOError