Decoding base64 from POST to use in PIL

Lazaro Gamio picture Lazaro Gamio · Sep 27, 2014 · Viewed 37k times · Source

I'm making a simple API in Flask that accepts an image encoded in base64, then decodes it for further processing using Pillow.

I've looked at some examples (1, 2, 3), and I think I get the gist of the process, but I keep getting an error where Pillow can't read the string I gave it.

Here's what I've got so far:

import cStringIO
from PIL import Image
import base64

data = request.form
image_string = cStringIO.StringIO(base64.b64decode(data['img']))
image = Image.open(image_string)

which gives the error:

IOError: cannot identify image file <cStringIO.StringIO object at 0x10f84c7a0>

Answer

Andr&#233; Teixeira picture André Teixeira · Sep 28, 2014

You should try something like:

from PIL import Image
from io import BytesIO
import base64

data['img'] = '''R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLl
N48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==''' 

im = Image.open(BytesIO(base64.b64decode(data['img'])))

Your data['img'] string should not include the HTML tags or the parameters data:image/jpeg;base64 that are in the example JSFiddle.

I've changed the image string for an example I took from Google just for readability purposes.