[英]Sending images over socket in Python 3
I am trying to send an image (screenshot) over socket from the client to the server. 我正在尝试通过套接字从客户端向服务器发送图像(屏幕快照)。 In Python 2 I was able to use the read()
and write()
function in order to read and write binary data as well as StringIO
. 在Python 2中,我能够使用read()
和write()
函数来读取和写入二进制数据以及StringIO
。 But all of them disappeared in Python 3. I was playing around with PIL
, but I can't get the test program running. 但是所有这些都在Python 3中消失了。我在玩PIL
,但是我无法运行测试程序。
CLIENT 客户
image = ImageGrab.grab()
s.send(image.tobytes())
I create a screenshot using GrabImage
and save it as image
. 我使用GrabImage
创建屏幕截图并将其另存为image
。 After that I send the image as binary over the socket to the server. 之后,我将图像作为二进制文件通过套接字发送到服务器。
SERVER 服务器
data = conn.recv(4194304)
img = Image.frombytes('RGB', (1366, 768), data)
img.save('screenshot.jpg')
However, If I run the script I get an error message: 但是,如果我运行脚本,则会收到错误消息:
ValueError: not enough image data
I think I'm missing something decisive, but I can't figure it out. 我想我缺少决定性的东西,但我无法弄清楚。
Thank you, chrizator. 谢谢你,主持人。
It's likely that the call to .recv()
is returning before all the data is retrieved; 在检索所有数据之前,很可能返回对.recv()
的调用。 the parameter is a maximum size, not an exact size. 该参数是最大大小,而不是确切大小。 You'll need to call .recv()
in a loop and append the data until the entire image is received. 您需要循环调用.recv()
并追加数据,直到接收到整个图像为止。 This implies that you'll need some way to know WHEN the entire data is received - common strategies for this are: 这意味着您需要某种方式来知道何时接收到全部数据-常见的策略是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.