1

I am trying to convert an byte array to PNG image and save it to a specific folder. The byte array comes from a C# server, python client will receive it and save as PNG image.

I tried the following way:

reply = s.recv(4096)
image = Image.open(io.BytesIO(reply))
image.save("img1.png","PNG")

It gives following error:

Traceback (most recent call last):
File "C:\Users\imran.s\Desktop\UnityClient.py", line 46, in <module>
 image.save("img1.png","PNG")

File "C:\python64\lib\site-packages\PIL\Image.py", line 1895, in save
self.load()

File "C:\python64\lib\site-packages\PIL\ImageFile.py", line 233, in load
"(%d bytes not processed)" % len(b))

OSError: image file is truncated (3 bytes not processed)
Daniel F
  • 13,620
  • 2
  • 29
  • 55
Imran Sikder
  • 73
  • 13

1 Answers1

0

You can use OpenCV image processing library if it not represents an overhead. OpenCV handles images open and saving and you can process it if needed.

If you data is in RGB format you can:

import cv2

# Loop to Load each pixel values in positions in array
for ...
   image[x, y] = (0, 0, 255) # B, G, R : different order

in your case if data is already byte-ordered in [(Blue, Green, Red), (), ... ,()]:

# Then to save: 
cv2.imwrite('img1.png',reply)
dpetrini
  • 1,169
  • 1
  • 12
  • 25