使用struct来处理,废话不说,直接上代码
import struct
import numpy as np
import cv2
def str2St(bStr):
return str(len(bStr)) + 's'
name = 'picture.jpg'
name_bin = name.encode('utf-8') #转二进制
img = cv2.imread(name) #ndarray类型,按bgr顺序排序,uint8类型
img_bin = img.tostring() #bytes类型 或者用tobytes()
namelen_uchar = len(name_bin) # B 1字节
width_ushort = img.shape[1] # H 2字节
height_ushort = img.shape[0] # H 2字节
datalen_uint = len(img_bin) # I 4 字节
#产生64字节的字串, 字串填充文件名
data = np.zeros(shape=(64),dtype='uint8')
data[0:namelen_uchar] = np.fromstring(name, dtype='uint8')
name_bytes = data.tobytes()
st = '<' # <小端, >大端, !网络顺序
st = st + str2St(name_bytes)
st = st + 'HHI'
st = st + str2St(img_bin)
#struct打包
pk = struct.pack(st, name_bytes, width_ushort, height_ushort, datalen_uint, img_bin)
#struct解包
name_bytes, width_ushort, height_ushort, databytes_uint, img_bin = struct.unpack(st, pk)
name = name_bytes.decode('utf8')
name = name[0:name.rfind('.')] + 'recv.jpg'
print(name)
#将二进制字节流转为numpy格式(ndarry)
img_recv = np.frombuffer(img_bin, dtype=np.uint8).reshape([height_ushort, width_ushort, 3])
cv2.imwrite(name, img_recv)