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

2024-04-19 23:44:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图操纵一个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']


Tags: 字符串图像imageformat编码stringhereexpand
1条回答
网友
1楼 · 发布于 2024-04-19 23:44:01

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

相关问题 更多 >