python - 将图像“拆分”成字节包
问题描述
我正在尝试为大学做一个项目,其中包括使用两个 Arduino Due 板和 Python 发送图像。我有两个代码:一个用于客户端(发送图像的那个),另一个用于服务器(接收图像的那个)。我知道如何发送字节并检查它们是否正确,但是,我需要将图像“拆分”为具有以下内容的包:
一个大小为 8 字节且必须按以下顺序排列的标头:
- 第一个字节必须说明有效载荷大小;
- 接下来的三个字节必须说明总共将发送多少个包;
- 接下来的三个字节必须说明我目前在哪个包;
- 最后一个字节必须包含错误消息的代码;
包含最大大小为 128 字节的数据的有效载荷;
- 包结束 (EOP) 序列(在本例中为 3 个字节)。
我设法创建了包序列的结尾并将其正确附加到有效负载以便发送,但是我在创建标头时遇到了问题。
我目前正在尝试进行以下循环:
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)
我希望最终服务器收到与客户端发送的相同数量的包,最后我需要加入这些包以重新创建图像。我可以做到这一点,我只需要一些帮助来创建标题。
解决方案
这是一个如何构建标题的演示,它不是一个完整的灵魂,但鉴于您只要求帮助构建标题,它可能是您正在寻找的。
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]}")
显然我没有包含获取当前包或总包的逻辑。
推荐阅读
- python - 如何在 Python 中使用信号模块或其他模块使 Paramiko sftp.put() 超时?
- javascript - 根据用户代理字符串转换链接
- python - 在 Odoo 中添加具有默认值的新布尔字段
- r - 使用 glmnet 的多项岭回归给出的结果概率高于 1,而对于不同的目标类别为负,知道为什么吗?
- python - 为什么我在尝试访问 HttpRequest.POST['choice'] 值时收到 TypeError?我该如何解决这个错误?
- python - numpy.einsum('ij,ji', a, b) 性能问题
- sql - 使用交叉表功能透视 SQL 表
- database - 规范化中的候选键
- android - 为什么片段不显示空白屏幕?
- ruby-on-rails - 如何通过助手传递标题?