Skip to content Skip to sidebar Skip to footer

How To Convert Byte Array To Image In Python

I am trying to convert raw data of length 64372(w= 242, h=266) to the image, the raw data is in the format of the byte array, I want to convert this byte array into image, can you

Solution 1:

You can generate a bytearray of dummy data representing a gradient like this:

import numpy as np

# Generate a left-right gradient 242 px wide by 266 pixels tall
ba = bytearray((np.arange(242) + np.zeros((266,1))).astype(np.uint8)) 

For reference, that array will contain data like this:

array([[  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.],
       ...,
       [  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.],
       [  0.,   1.,   2., ..., 239., 240., 241.]])

And then make into a PIL/Pillow image like this:

from PIL import Image

# Convert bytearray "ba" to PIL Image, 'L' just means greyscale/lightness
im = Image.frombuffer('L', (242,266), ba, 'raw', 'L', 0, 1)

Then you can save the image like this:

im.save('result.png')

enter image description here

Documentation is here.

Post a Comment for "How To Convert Byte Array To Image In Python"