How to send images via socket in Python?

0

So there's the server:

import socket
from PIL import Image
port = 8000
host = '127.0.0.1'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((host, port))
s.listen(5)



while True:
    conn, addr = s.accept()
    print('Conectado a {}'.format(addr))
    with open('logo_python.png', 'rb') as f:
        conn.send(f.read())
        l = f.read()
    #im = Image.open(l)
    #im.show()
        f.close()

print('Arquivo enviado')

And the client:

import socket
from PIL import Image
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

print("Recebendo Dados...\n")
with open('recebido.png', 'wb') as f:
        print('file opened')
        print('Recebendo dados...')
        data = s.recv(4000)
        f.write(data)
        print(data)
        print("ENVIADO")
        f.close()
with open('recebido.png', 'rb') as f:
        im = Image.open(f)
        im.show()

print('Transferência completa!!!')
s.close()
print('Conexão encerrada.')

The error that appears:

    File "C:/Users/Diego Cândido/PycharmProjects/servarq/ClienteTeste.py", line 18, in <module>
    im = Image.open(f)
  File "C:\Users\Diego Cândido\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2618, in open
    prefix = fp.read(16)
  File "C:\Users\Diego Cândido\AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 172: character maps to <undefined>

Basically what the server is sending to the client is:

b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x02Y\x00\x00\x00\xcb\x08\x06\x00\x00\x00]\xc9\x86&\x00\x00\x00\x04sBIT\x08\x08\x08\x08 #... e assim por diante
    
asked by anonymous 14.11.2018 / 03:08

1 answer

1

EDIT: Now with the code and the error it was much easier to help.

UnicodeDecodeError occurs when trying to transform a string of bytes that does not match the encoding used.

By the text of the error, it appears that it is using the charmap encoding cp1252; This would only occur if you were trying to run the .decode() method or if you had opened the file in text mode (not binary); When you open a text-mode file, the python does automatic decoding .

In the code that you pasted the question has the letter 'b' in open , which indicates binary mode:

with open('recebido.png', 'rb') as f:

To check if there was any mistake, I ran a test with a JPG file that I downloaded here , I called of diego.jpg . I opened it in text mode, without the letter b :

>>> f = open('diego.jpg', 'r', encoding='cp1252') # sem o 'b'
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/encodings/cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 383: character maps to <undefined>

As you can see the error was very similar to yours - I believe that when testing, it must have confused the files and left the open() without the b , and therefore received the error that pasted, I can not see another reason.

I then tried your code above , but with this file diego.jpg I downloaded it. I just changed the filename from logo_python.png to diego.jpg and circled the server.

I renamed the file from recebido.png to recebido.jpg and circled the client. You gave the following error:

Traceback (most recent call last):
  File "cliente.py", line 19, in <module>
    im.show()
#  ( ... )
  File "/usr/lib/python3/dist-packages/PIL/Image.py", line 1982, in show
    _show(self, title=title, command=command)
  File "/usr/lib/python3/dist-packages/PIL/ImageFile.py", line 228, in load
    "(%d bytes not processed)" % len(b))
OSError: image file is truncated (3 bytes not processed)

As you can see, 4000 bytes is not enough to transfer the image. I edited the client again, and increased the number to 6502 (which is exactly the size of the image diego.jpg ):

Inshort:Itworked,yourcodeis"working", the error you are having is impossible to occur with the code of the form you put in the question, there must be some mistake. The only thing I changed was the number of bytes, which should be exactly the size of the image, because with fewer bytes it is not possible to open the image.

    
14.11.2018 / 04:04