0

I would like to send images with socketserver of python 3 and I have a problem of encoding. Do I need to send it in bytes or in text? And do I need to open my image with the 'b' option and to transform it in a particular format?

With previous version of python I could do :

image = open('my_image.jpg', 'rb')
image_data = image.read()
image.close()

socketData = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socketData.connect((ADDRESS,PORT))

socketData.sendall(image_data)

But with python 3, it doesn't work anymore. There are encoding and codecs problems and I don't really understand the using of encode(), decode() or str().

Do you have any idea how I can implement it?

Thanks

Loric
  • 1,678
  • 8
  • 28
  • 48
  • Really? [It seems to work for me](http://i.imgur.com/h3wvN.png). What specific error are you getting? – Fredrick Brennan Jan 10 '13 at 13:35
  • In fact, a explained my problem badly. There is something I forgot to add : I have a header to add to my image for my client and my header is in text format. So when I send my data, I have something like this : socketData.sendall(header + image_data) And the error is : Can't convert 'bytes' object to str implicitly Do I need to convert my header in bytes (if yes how :/) or my image in text ? – Loric Jan 10 '13 at 13:43
  • I can send it separately and it works, so it solved my problem! Thank you so much! – Loric Jan 10 '13 at 13:49

1 Answers1

0

Like I wrote above, your code works as-is currently. To add a header to the data that you want to send over the socket, you first need to know its encoding. Assuming that it is UTF-8, you can do the following:

header = "Header!\n"
header_bytes = bytes(header, 'utf-8')
socketData.sendall(header_bytes + image_data)

bytes type can only be concatenated with bytes in Python 3.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Fredrick Brennan
  • 7,079
  • 2
  • 30
  • 61