Converting hex data to image
Peter Otten
__peter__ at web.de
Mon Mar 11 07:02:14 EDT 2019
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:
>
\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff\xdb\x00C\x00
> 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)
More information about the Python-list
mailing list