receive image data

This commit is contained in:
ktyl 2023-02-18 01:37:47 +00:00
parent a86074f089
commit 60d9c11e50
1 changed files with 43 additions and 2 deletions

View File

@ -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!")