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

310 Views Asked by At

I'm working on a socket data transfer project. I want to watch client screen. I'm using pillow and pickle module both server and client but when I trying to send ImageGrab.grab() object, object size is 3Mb. It's very high data for transferring. Although object size is 3MB, saved size (ImageGrab.grab().save("example.jpg")) is 200 kb. When i save file then read saved photo for transferring, it cause very high cpu usage. Even i try to send bytes of object -> ImageGrab.grab().tobytes() <- , its again 3mb. How can i send only data of image from object without saving file ?

2

There are 2 best solutions below

0
Ertuğrul Çakıcı On BEST ANSWER

I solved this problem through IO

from PIL import Image, ImageGrab
a = ImageGrab.grab()
import io
b = io.BytesIO()
a.save(b, "JPEG")
len(b.getbuffer())
224455
3
Epsi95 On

here is a working example

server

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()

client

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()