[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Converting hex data to image

dimplemathew.17 at gmail.com wrote:

> Hi i have a similar challenge where i need to store the thumbnailPhoto
> attribute to my local db and display the image every-time user logs in.
> But this solution does work . data looks like this:

> import PIL
> from PIL import Image
> import io
> data = open("bytes.txt")
> my_data=(data.read())
> photo_inline = io.StringIO(my_data)
> photo = PIL.Image.open(photo_inline)
> error:
> Traceback (most recent call last):
> File "convertToImage.py", line 9, in <module>
> photo = PIL.Image.open(photo_inline)
> File "", line 2657, in open
> % (filename if filename else fp))
> OSError: cannot identify image file <_io.StringIO object at 0x0367FD00>

Did you try

photo = PIL.Image.open("bytes.txt")


If the above code is illustrative, and you really need the bytes in memory 
remember to open the file in binary mode:

with open("bytes.txt", "rb") as instream:
    data = instream.read()

To create the image later the file-like objects needs to produce bytes:

instream = io.BytesIO(data)  # not StringIO!
photo = Image.open(instream)