How to convert PIL Image.image object to base64 string? [duplicate]
Asked Answered
E

1

76

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']

Eightieth answered 5/8, 2015 at 7:43 Comment(0)
S
187

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())
Shoop answered 5/8, 2015 at 7:50 Comment(11)
I'd like to say that in python3.4 you should write from io import BytesIO and buffer = BytesIO(). Also keep in mind that buffer is already an existing builtin name (use buffered maybe). The fine docs.Polynuclear
IOError: cannot write mode RGBA as JPEGBraud
@Braud this means image has alpha channel (known as transparency level in your image). In case you are safe to get rid of it, you can convert image to RGB before saving it to and converting to base64 string with next line: image = image.convert("RGB")Shoop
If someone what to write to an image, this is neccessary img_base64 = bytes("data:image/jpeg;base64,", encoding='utf-8') + img_strPe
@Braud See github.com/python-pillow/Pillow/issues/… for a workaroundTiatiana
@VictorJohn Really...?Tiatiana
Sorry but does not work: I get a string like "b'iVBORw0KGgoAAAA....", aka the byte string...what I want is the canonical base64 string the one ending with "==" ...Cuttlefish
@Phate, what did you do on this ?Roomy
@LutaayaHuzaifahIdris from django.utils.encoding import force_str then force_str(img_str)Hyksos
@Cuttlefish Use .decode("<format>"). For example: img_base64_str = img_base64.decode("utf-8")Stalder
is there a way to compress the image string and reduce its size?Yung

© 2022 - 2024 — McMap. All rights reserved.