Wednesday, May 1, 2019

A second image client

This one is quite different from the previous client. It sends the width and height of the image to the server, and reconstitutes the pickled Image object from the byte stream the server sends back. It then uses pygame to display the image in a window, and does that as fast as it can. The width and height default to 300x300, but can be altered from the command line.



#!/usr/bin/env python3

import socket
import sys
import argparse
import pickle
import pygame
from PIL import Image

parser = argparse.ArgumentParser(description='Explorer (fake) client.')
parser.add_argument('--hostip', '-i', action='store', dest='address', 
        default='127.0.0.1', help='IP address of server host.')
parser.add_argument('--port', '-p', action='store', type=int, dest='port',
        default=12345, help='Port number.')
parser.add_argument('--height', '-y', action='store', type=int, dest='height',
        default=300, help='Image height.')
parser.add_argument('--width', '-x', action='store', type=int, dest='width',
        default=300, help='Image width.')
parser.add_argument('--debug', '-d', action='store_true', default=False,
        dest='debug', help='Print debugging information.')
args = parser.parse_args()

def get_image(width=300, height=300):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        data = b''
        sock.connect((args.address, args.port))
        sock.sendall(bytes('{} {}'.format(width, height), 'utf-8'))
        while True:
            received = sock.recv(4069)
            if not received: break
            data = data + received
        sock.close()
        if args.debug: print('Received {} bytes'.format(len(data)))
    return pickle.loads(data)

pygame.init()
display_surface = pygame.display.set_mode((args.width, args.height))
pygame.display.set_caption('Picam')

try:
    while True:
        picture = get_image(width=args.width, height=args.height)
        data = picture.tobytes()
        img = pygame.image.fromstring(data, picture.size, 'RGB')
        display_surface.blit(img, (0, 0))
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
except KeyboardInterrupt:
    pass




No comments:

Post a Comment