简体   繁体   English

如何在Python 3中通过SocketServer发送图像?

[英]How to send Images via SocketServer in Python 3?

I would like to send images with socketserver of python 3 and I have a problem of encoding. 我想使用python 3的socketserver发送图像,但是我有编码问题。 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? 我是否需要使用'b'选项打开图像并将其转换为特定格式?

With previous version of python I could do : 使用以前的python版本,我可以做到:

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. 但是使用python 3,它不再起作用了。 There are encoding and codecs problems and I don't really understand the using of encode(), decode() or str(). 存在编码和编解码器问题,我不太了解如何使用encode(),decode()或str()。

Do you have any idea how I can implement it? 您是否知道如何实施?

Thanks 谢谢

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: 假设它是UTF-8,则可以执行以下操作:

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. bytes类型只能在Python 3中与bytes连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM