Converting hex data to image

Ben Finney ben+python at
Thu Nov 14 22:09:09 CET 2013

Shyam Parimal Katti <spk265 at> writes:

> When we fetch the data from the LDAP server for a particular valid
> user, the data associated with the user contains the thumbnail photo
> in hex representation. E.x.:
> [('CN=XX,OU=Users,OU=Accounts,DC=test,DC=com', {'msExchBlockedSendersHash':
> ['\xce'], 'mailNickname': ['test_user'], 'primaryGroupID': ['513'],
> 'logonCount': ['1021'], *thumbnailPhoto:
> ['\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.....']*......
> ]

So the image data appears to be a byte string, is that right? You can
use the Pillow library <URL:> to
process graphic images to and from bytes.

To turn a byte string into a file-like object for use with PIL, extract
the byte string as ‘image_data’, use the standard library ‘io.StringIO’
class <URL:>, then
create a new ‘PIL.Image’ object by reading from that pseudo-file::

    import io

    import PIL

    photo_data = # … get the byte string from wherever it is …
    photo_infile = io.StringIO(photo_data)
    photo_image = PIL.Image.frombytes(photo_infile)

> How do I convert the hex data for an image to the actual image?

It depends on what you think “the actual image” is, if not the bytes
themselves. There's no native Python “graphic image” data type; if the
bytes are not the representation you want, you need to choose some other
representation of that image.

Using a ‘PIL.Image’ object as the representation, you can perform all
kinds of further manipulations of a graphic image

 \      “It seems intuitively obvious to me, which means that it might |
  `\                                           be wrong.” —Chris Torek |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list