How to convert PIL Image.image object to base64 string?

PythonPython Imaging-Library

Python Problem Overview


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.

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.

here's the dir() of 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']

Python Solutions


Solution 1 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHammad QureshiView Question on Stackoverflow
Solution 1 - PythonEugene VView Answer on Stackoverflow