PIL with BytesIO: cannot identify image file

ajflj picture ajflj · May 11, 2017 · Viewed 7k times · Source

I am trying to send an image over socket connection for video chat, but the reconstruction of the image from bytes format is incorrect. Here is my conversion of the image to bytes to send:

pil_im = Image.fromarray(img)
b = io.BytesIO()
pil_im.save(b, 'jpeg')
im_bytes = b.getvalue()
return im_bytes

This sends fine, however, I cannot resolve the reformatting of these bytes into an image file. Here is my code to reformat into image for display:

pil_bytes = io.BytesIO(im_bytes)
pil_image = Image.open(pil_bytes)
cv_image = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
return cv_image

The second line there raises the following exception:

cannot identify image file <_io.BytesIO object at 0x0388EF60>

I have looked at some other threads (this one and this one) but no solution has been helpful for me. I am also using this as reference to try to correct myself, but what seems to work fine for them just doesn't for me. Thank you for any assistance you can provide and please excuse any errors, I am still learning python.

Answer

Rami Alloush picture Rami Alloush · Feb 25, 2019

First of all Thank You! as the code in your question helped me to solve the first part of the problem I had. The second part was already solved for me using this simple code (don't convert to array)

dataBytesIO = io.BytesIO(im_bytes)
image = Image.open(dataBytesIO)

Hope this helps