BytesIO object to image

11,721

I'm not sure what the resulting image should look like (do you have an example?), but if you want to unpack an packed image where each pixel has 12 bits into a 16-bit image, you could use this code:

import io
from PIL import Image

rawbytes = b'_\x00`\x00[\x00^\x00`\x00`\x00\\\x00\\\x00Z\x00\\\x00_\x00[\x00\\\x00\\\x00`\x00]\x00\\\x00^\x00_\x00\\\x00\\\x00]\x00]\x00_\x00]\x00]\x00Z\x00\\\x00^\x00\\\x00Z\x00^\x00_\x00]\x00^\x00Z\x00\\\x00Z\x00\\\x00]\x00_\x00]\x00^\x00Z\x00[\x00[\x00X\x00]\x00]\x00Z\x00'
im = Image.frombuffer("I;16", (5, 10), rawbytes, "raw", "I;12")
im.show()
Share:
11,721
smiddy84
Author by

smiddy84

Updated on June 14, 2022

Comments

  • smiddy84
    smiddy84 almost 2 years

    I'm trying to use Pillow in my program to save a bytestring from my camera to a file. Here's an example with a small raw byte string from my camera which should represent a greyscale image of resolution 10x5 pixels, using LSB and 12bit:

    import io
    from PIL import Image
    
    rawBytes = b'_\x00`\x00[\x00^\x00`\x00`\x00\\\x00\\\x00Z\x00\\\x00_\x00[\x00\\\x00\\\x00`\x00]\x00\\\x00^\x00_\x00\\\x00\\\x00]\x00]\x00_\x00]\x00]\x00Z\x00\\\x00^\x00\\\x00Z\x00^\x00_\x00]\x00^\x00Z\x00\\\x00Z\x00\\\x00]\x00_\x00]\x00^\x00Z\x00[\x00[\x00X\x00]\x00]\x00Z\x00'
    rawIO = io.BytesIO(rawBytes)
    rawIO.seek(0)
    byteImg = Image.open(rawIO)
    byteImg.save('test.png', 'PNG')
    

    However I get the following error in line 7 (with Image.open):

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

    The docs from Pillow implied this was the way to go.

    I tried to apply the solutions from

    but can't get it working. Why isn't this working?

  • smiddy84
    smiddy84 over 8 years
    Thanks for the tip! In my case, the output was a Windows WORD type (so 16-bit little endian unsigned integer). In the end, having a look at the decoder description, I was able to decode my image correctly: Image.frombuffer("F", (10, 5), rawbytes, "raw", "F;16")
  • Michiel Overtoom
    Michiel Overtoom over 8 years
    I'm glad the frombuffer() function did for you what you required, and that my suggestion put you on the right track. I did have to delve into the pillow source code to find this solution, however ;-)