Converting hex data to image
Peter Otten
__peter__ at web.de
Tue Mar 12 04:38:42 EDT 2019
dimplemathew.17 at gmail.com wrote:
> On Monday, March 11, 2019 at 4:32:48 PM UTC+5:30, Peter Otten wrote:
>> 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)
>
> Hey,
> It shows the same error.
> I am actually getting that image from ldap in bytes:
>
'\xef\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c.....
> I want to display this image on my template.
Save the image to a file (in binary mode!) and then try to open it with an
image viewer. The data may be corrupted.
More information about the Python-list
mailing list