From 60d9c11e500c11a6d21b9407a15f85ad157b97c6 Mon Sep 17 00:00:00 2001 From: ktyl Date: Sat, 18 Feb 2023 01:37:47 +0000 Subject: [PATCH] receive image data --- src/viewer.py | 45 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/src/viewer.py b/src/viewer.py index 64d4b47..d115545 100644 --- a/src/viewer.py +++ b/src/viewer.py @@ -1,10 +1,51 @@ import socket +import struct sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", 64999)) recv_limit = 1024 +filename = "image.ppm" -received = sock.recv(recv_limit) -print(received) +ppm_data = b"" + +# TODO: write to file while still receivinig data, for more speed! +# receive data from server +while True: + data = sock.recv(recv_limit) + if not data: + break + + ppm_data += data + +# .ppm format: +# P3 +# WIDTH HEIGHT +# MAXIMUM_COLOR_VALUE +# PIXEL_DATA + +# read the image data and write it into a file +with open(filename, "w") as file: + + # read image dimensions from first 8 bytes (2 ints) + dimensions = struct.unpack("!ii", ppm_data[0:8]); + width = dimensions[0] + height = dimensions[1] + maximum_value = 255 + + # write file header + file.write("P3\n") + file.write(f"{width} {height}\n") + file.write(f"{maximum_value}\n") + + # a pixel is 3 bytes, so we should expect the data + # block to be 3 * length long + length = dimensions[0] * dimensions[1] + data = ppm_data[8:] + + for i in range(0, len(data), 3): + line = f"{data[i]} {data[i+1]} {data[i+2]}\n" + file.write(line) + +print("done!")