我正在处理一个套接字数据传输项目。我想看客户端屏幕。我在服务器和客户端都使用pillow和pickle模块,但当我尝试发送ImageGrab.grab((对象时,对象大小是3Mb。这是非常高的数据传输。虽然对象大小是3MB,但保存的大小(ImageGrab.grab((.save("example.jpg"((是200kb。当我保存文件,然后读取保存的照片进行传输时,这会导致非常高的cpu使用率。即使我尝试发送对象的字节->ImageGrab.grab((.tobytes((<-,再次为3mb。如何在不保存文件的情况下只发送对象的图像数据?
我通过IO 解决了这个问题
from PIL import Image, ImageGrab
a = ImageGrab.grab()
import io
b = io.BytesIO()
a.save(b, "JPEG")
len(b.getbuffer())
224455
这里有一个的工作示例
服务器
import socket
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
plt.figure(1)
host = socket.gethostname()
port = 8080
server_socket = socket.socket()
server_socket.bind((host, port))
server_socket.listen()
conn, address = server_socket.accept()
print("Connection from: " + str(address))
image_data = b''
while True:
data = conn.recv(1024*4) # 4kb data
print('received data')
if(data != 'EOD'.encode()):
image_data+=data
else:
image = Image.frombytes('RGB', (800, 800), image_data, 'raw')
plt.clf()
plt.imshow(np.asarray(image))
plt.pause(1)
#plt.show()
image_data = b''
conn.close()
客户端
import socket
import pyautogui
import time
host = socket.gethostname()
port = 8080
client_socket = socket.socket()
client_socket.connect((host, port))
while True:
image = pyautogui.screenshot()
print('took screen shot')
image = image.resize(size=(800, 800)) # configure the size using image.size to maintain proper aspect ratio
client_socket.sendall(image.tobytes())
time.sleep(2)
client_socket.send('EOD'.encode())
client_socket.close()