Python 如何将 PIL Image.image 对象转换为 base64 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31826335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert PIL Image.image object to base64 string?
提问by Hammad Qureshi
I am trying to manipulate a base64 encoded image in such a way as to rotate it at 90 angle. After this manipulation, I want to convert it back to base64 string. But unfortunately unable to achieve this yet.
我试图以 90 角旋转它的方式操作 base64 编码的图像。在此操作之后,我想将其转换回 base64 字符串。但遗憾的是目前还无法实现。
Here is what I have done so far:
这是我到目前为止所做的:
image_string = StringIO(base64.b64decode(base64_string_here))
image = Image.open(image_string)
angle = 90
rotated_image = image.rotate( angle, expand=1 )
Kindy help me how to convert this rotated_image to base64 string.
好心帮我如何将这个rotated_image 转换为base64 字符串。
here's the dir()
of rotated_image:
这dir()
是rotated_image的:
['_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']
['_Image__transformer', '__doc__', '__getattr__', '__init__', '__module__', '__repr__', '_copy', '_dump', '_expand', '_makeself', '_new', 'category', '转换','复制','裁剪','草稿','过滤器','格式','format_description','fromstring','getbands','getbbox','getcolors','getdata','getextrema' , 'getim', 'getpalette', 'getpixel', 'getprojection', 'histogram', 'im', 'info', 'load', 'mode', 'offset', 'palette', 'paste', '点','putalpha','putdata','putpalette','putpixel','量化','readonly', 'resize', 'rotate', 'save', 'seek', 'show', 'size', 'split', 'tell', 'thumbnail', 'tobitmap', 'tostring', 'transform' ', '转置', '验证']
采纳答案by user3255354
Python 3
蟒蛇 3
import base64
from io import BytesIO
buffered = BytesIO()
image.save(buffered, format="JPEG")
img_str = base64.b64encode(buffered.getvalue())
Python 2
蟒蛇 2
import base64
import cStringIO
buffer = cStringIO.StringIO()
image.save(buffer, format="JPEG")
img_str = base64.b64encode(buffer.getvalue())