wayne
wayne

Reputation: 101

PIL open image from base64 failed

I'm trying to convert a base64 string to image and get the following error.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2288, in open
    % (filename if filename else fp))
IOError: cannot identify image file <cStringIO.StringI object at 0x7fe6d9e88828>

There is no prefix like data:image/png;base64. I get the base64 string from an image and try to convert it back to an image. Here is my code.

# -*- coding: utf-8 -*-

import requests
import base64
from PIL import Image
from cStringIO import StringIO
import zipfile

r = requests.get('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png', stream=False)
img = Image.open(StringIO(r.content))
b64str = base64.b64encode(img.tobytes())

data = base64.b64decode(b64str)
newimg = Image.open(StringIO(data))

And I get the error above. Can anyone help? Thanks!

Upvotes: 1

Views: 481

Answers (1)

lenik
lenik

Reputation: 23498

You open .PNG file from the web and get the RAW image, which is RGB values, then encode that into base64 and back, which still gives you RAW RGB values which cannot be read by Image.open() because these are not an image file (jpg, png, etc), but RAW RGB values.

The most reasonable would be:

newImg = data  # that's it

Or if you want to make an Image:

newImg = Image.frombytes(img.mode, img.size, data)

and get mode and size from the original image.

Upvotes: 3

Related Questions