如何减小在 Python 中通过 pickle 转储的图像对象大小

How to decrease Image object size that dumped through pickle in Python

我正在做一个套接字数据传输项目。我想看客户端屏幕。我在服务器和客户端都使用 pillow 和 pickle 模块,但是当我尝试发送 ImageGrab.grab() 对象时,对象大小为 3Mb。这是非常高的传输数据。尽管对象大小为 3MB,但保存的大小 (ImageGrab.grab().save("example.jpg")) 为 200 kb。当我保存文件然后读取保存的照片进行传输时,它会导致非常高的 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()