图片在网络传输中的转码问题
使用opencv打开图片后得到numpy.array的数据格式。
以下代码实现 ndarray 到 base64 到 string 的转换
def img_test(filepath):
img = cv2.imread(filepath)
oshape = img.shape
# print(img.shape) #ndarray
# code_base64 = base64.b64encode(img)
code_base64 = base64.urlsafe_b64encode(img) # ndarray 转 base64
# print(code_base64)
code_str = str(code_base64, "utf-8") # base64 转 string
# print(code_str)
decode_str = codecs.encode(code_str, 'utf-8') # string 转 base64
# print(decode_str)
# decode_base64 = base64.b64decode(decode_str)
decode_base64 = base64.urlsafe_b64decode(decode_str) # base64 解码
np_img = np.frombuffer(decode_base64, dtype=np.uint8) # bytes 转 ndarray
# print(np_img.shape)
np_img = np_img.reshape(oshape) # 还原图片
# print(np_img)
cv2.imshow("text1", np_img)
cv2.waitKey()