PIL cannot identify image file for io.BytesIO object

Elan M picture Elan M · Jun 26, 2015 · Viewed 88.3k times · Source

I am using the Pillow fork of PIL and keep receiving the error

OSError: cannot identify image file <_io.BytesIO object at 0x103a47468>

when trying to open an image. I am using virtualenv with python 3.4 and no installation of PIL.

I have tried to find a solution to this based on others encountering the same problem, however, those solutions did not work for me. Here is my code:

from PIL import Image
import io

# This portion is part of my test code
byteImg = Image.open("some/location/to/a/file/in/my/directories.png").tobytes()

# Non test code
dataBytesIO = io.BytesIO(byteImg)
Image.open(dataBytesIO) # <- Error here

The image exists in the initial opening of the file and it gets converted to bytes. This appears to work for almost everyone else but I can't figure out why it fails for me.

EDIT:

dataBytesIO.seek(0)

does not work as a solution (tried it) since I'm not saving the image via a stream, I'm just instantiating the BytesIO with data, therefore (if I'm thinking of this correctly) seek should already be at 0.

Answer

sdikby picture sdikby · Sep 24, 2017

(This solution is from the author himself. I have just moved it here.)

SOLUTION:

# This portion is part of my test code
byteImgIO = io.BytesIO()
byteImg = Image.open("some/location/to/a/file/in/my/directories.png")
byteImg.save(byteImgIO, "PNG")
byteImgIO.seek(0)
byteImg = byteImgIO.read()


# Non test code
dataBytesIO = io.BytesIO(byteImg)
Image.open(dataBytesIO)

The problem was with the way that Image.tobytes()was returning the byte object. It appeared to be invalid data and the 'encoding' couldn't be anything other than raw which still appeared to output wrong data since almost every byte appeared in the format \xff\. However, saving the bytes via BytesIO and using the .read() function to read the entire image gave the correct bytes that when needed later could actually be used.