[英]Send PIL image object from socket client to socket server
I want to send a PIL image object from a socket client to a socket server.我想将 PIL 图像对象从套接字客户端发送到套接字服务器。 Since I cannot send the image object directly over the socket, I have converted it into an array using numpy, then tried to send the array over to the socket server.
由于我无法直接通过套接字发送图像对象,因此我使用 numpy 将其转换为数组,然后尝试将数组发送到套接字服务器。
Here is my server program (the time
thing is just to get a new name for the file every time I save it):这是我的服务器程序(
time
只是在我每次保存文件时为文件取一个新名称):
import socket
import time
import os
import sys
import Image
import ImageGrab
import numpy
sd='C:\Users\Saurabh\Desktop'
s=socket.socket()
host=socket.gethostname() #'WarMachine'
port=12300
s.bind((host,port))
s.listen(9)
while True:
a,addr=s.accept()
print "got connection from",addr
a.send("1")
imgarr=a.recvfrom(4096)
img=Image.fromarray(numpy.uint8(imgarr))
sec=time.time()
lc=time.localtime(sec)
t=time.asctime(lc)
print t
strng=""+t[8:10]+"_"+t[11:13]+"_"+t[14:16]+"_"+t[17:19]
saveas=os.path.join(sd, 'ScreenShot_'+strng+'.jpg')
img.save(saveas)
print "run successful server"
a.close()
Error in Client program mentioned above is:上面提到的客户端程序中的错误是:
got connection from ('192.168.1.9', 50903)
Traceback (most recent call last):
File "C:/Users/Saurabh/PycharmProjects/MajorProject/srvr.py", line 26, in <module>
img=Image.fromarray(numpy.uint8(imgstr))
ValueError: invalid literal for long() with base 10: ''
And here's the client program:这是客户端程序:
import os
import sys
import time
import Image
import ImageGrab
import subprocess
import socket
import numpy
s=socket.socket()
host="WarMachine" #use same hostname as server or else it wont work
port=12300
s.connect((host,port))
def shtDwn():
time = 10
subprocess.call(["shutdown.exe", "/s"])
def screenShot():
sd='C:\Users\Saurabh\Desktop'
img=ImageGrab.grab()
imgarr=numpy.asarray(img)
s.send(imgarr)
print "run successful screentest1"
ip=s.recv(1024)
#this receives 1 sent from server to activate snapshot function
if (ip=="1"):
for i in range(0,10):
screenShot()
time.sleep(5)
elif(ip=="2"):
shtDwn()
else:
print"Wrong Input"
The error I am getting in above client program is:我在上面的客户端程序中遇到的错误是:
run successful screentest1
Traceback (most recent call last):
File "C:/Users/Saurabh/PycharmProjects/MajorProject/ScreenTest1.py", line 42, in <module>
screenShot()
File "C:/Users/Saurabh/PycharmProjects/MajorProject/ScreenTest1.py", line 27, in screenShot
s.sendto(imgarr,("WarMachine",12300))
socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host
By the way, I have saved images before using the program below, but I don't know what's wrong in my program above.顺便说一句,我在使用下面的程序之前保存了图像,但我不知道我上面的程序有什么问题。
Previous program without client and server:以前没有客户端和服务器的程序:
import os
import sys
import Image
import time
import ImageGrab
import numpy
sd='C:\Users\Saurabh\Desktop'
img=ImageGrab.grab()
imgarr=numpy.asarray(img)
print imgarr
img2=Image.fromarray(numpy.uint8(imgarr))
sec=time.time()
lc=time.localtime(sec)
t=time.asctime(lc)
print t
strng=""+t[8:10]+"_"+t[11:13]+"_"+t[14:16]+"_"+t[17:19]
saveas=os.path.join(sd, 'ScreenShot_'+strng+'.jpg')
#img.save(saveas)
img2.save(saveas)
print "run successful"
Well I also have been working on this problem and figured out that you can send an image over socket by converting it into numpy array.好吧,我也一直在研究这个问题,并发现您可以通过将图像转换为 numpy 数组来通过套接字发送图像。
Here's the sample code-这是示例代码-
#Host Side script
#Host will be sending the screen to client.
import numpy as np
import socket
from PIL import ImageGrab
filename = 'host_data.npy'
print("started.\nListening for connections...")
s = socket.socket()
s.bind((socket.gethostname(), 1234))
s.listen(0)
conn, addr = s.accept()
print('connection established.')
img = np.array(ImageGrab.grab())
np.save(filename, img)
file = open(filename, 'rb')
data = file.read(1024)
conn.send(data)
while data != b'':
data = file.read(1024)
conn.send(data)
print('data has been successfully transmitted.')
#This is client side script
import socket
import numpy as np
import cv2
s = socket.socket()
s.connect((socket.gethostname(), 1234))
print("connected.")
filename = 'client_data.npy'
file = open(filename, 'wb')
data = s.recv(1024)
file.write(data)
while data != b'':
data = s.recv(1024)
file.write(data)
file.close()
o_file = np.load(filename)
o_file = cv2.cvtColor(o_file, cv2.COLOR_BGR2RGB)
cv2.imshow('transferred file', o_file)
cv2.waitKey(0)
All I did is, save the numpy array in npy
file using np.save(filename)
and send the contents of the npy
files in bytes format.我所做的就是,使用
np.save(filename)
将 numpy 数组保存在npy
文件中,并以字节格式发送npy
文件的内容。 Then the Client received the contents and made another file of type npy
and loaded the array.然后客户
npy
收到内容并制作另一个类型为npy
文件并加载数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.