首页 > 解决方案 > 将图像“拆分”成字节包

问题描述

我正在尝试为大学做一个项目,其中包括使用两个 Arduino Due 板和 Python 发送图像。我有两个代码:一个用于客户端(发送图像的那个),另一个用于服务器(接收图像的那个)。我知道如何发送字节并检查它们是否正确,但是,我需要将图像“拆分”为具有以下内容的包:

我设法创建了包序列的结尾并将其正确附加到有效负载以便发送,但是我在创建标头时遇到了问题。

我目前正在尝试进行以下循环:

with open(root.filename, 'rb') as f:
    picture = f.read()

picture_size = len(picture)

packages = ceil(picture_size/128)
last_pack_size = (picture_size)

EOPs = 0
EOP_bytes = [b'\x15', b'\xff', b'\xd9']

for p in range(1,packages):
    read_bytes = [None, int.to_bytes(picture[(p-1)*128], 1, 'big'), 
        int.to_bytes(picture[(p-1)*128 + 1], 1, 'big')]
    if p != packages:
        endrange = p*128+1
    else:
        endrange = picture_size
    for i in range((p-1)*128 + 2, endrange):
        read_bytes.append(int.to_bytes(picture[i], 1, 'big'))
        read_bytes.pop(0)
        if read_bytes == EOP_bytes:
            EOPs += 1
    print("read_bytes:", read_bytes)
    print("EOP_bytes:", EOP_bytes)
    print("EOPs", EOPs)

我希望最终服务器收到与客户端发送的相同数量的包,最后我需要加入这些包以重新创建图像。我可以做到这一点,我只需要一些帮助来创建标题。

标签: pythonarduino

解决方案


这是一个如何构建标题的演示,它不是一个完整的灵魂,但鉴于您只要求帮助构建标题,它可能是您正在寻找的。

headerArray = bytearray()

def Main():
    global headerArray

    # Sample Data
    payloadSize = 254 # 0 - 254
    totalPackages = 1
    currentPackage = 1
    errorCode = 101   # 0 - 254

    AddToByteArray(payloadSize,1)    # the first byte must say the payload size;
    AddToByteArray(totalPackages,3)  # the next three bytes must say how many packages will be sent in total;
    AddToByteArray(currentPackage,3) # the next three bytes must say which package I'm currently at;
    AddToByteArray(errorCode,1)      # the last byte must contain a code to an error message;

def AddToByteArray(value,numberOfBytes):
    global headerArray

    allocate = value.to_bytes(numberOfBytes, 'little')
    headerArray += allocate

Main()

# Output

print(f"Byte Array: {headerArray}")

for i in range(0,len(headerArray)):
    print(f"Byte Position: {i} Value:{headerArray[i]}")

显然我没有包含获取当前包或总包的逻辑。


推荐阅读