Reputation: 2830
My python socked receives a PNG image as encoded bytearray
.
The image originally has RGBA32
format and a resolution of 160 x 90
. After encoding it, I receive a bytearray
with a length of 31529
(as opposed to the raw data size, which should be 160 * 90 * 4 = 57600
) bytes.
How can I decode this bytearray
again and 1) display it with the PIL library and 2) convert it to a numpy array to work with the data?
I tried using the Image module from PIL (with received_data
being my bytearray
):
import PIL.Image as Image
# socket code...
Image.frombytes('RGBA', (160, 90), received_data)
but get the following error:
argument 1 must be read-only bytes-like object, not bytearray
Edit:
Following @thshea suggestion, I changed the code to
Image.frombytes('RGBA', (160, 90), bytes(received_data))
, which resolves the error above. However, the function still seems to expect raw image data and I get the this error:
not enough image data
Furthermore, I think this is meant to take raw data, with the option to write a custom decoder?
Upvotes: 0
Views: 1598
Reputation: 6776
There's probably some better way, but wrapping the bytearray in a BytesIO
object and giving it to PIL as an open file should do it:
import io
f = io.BytesIO(received_data)
im = Image.open(f)
Upvotes: 1