图片传输中的转码问题

图片在网络传输中的转码问题

使用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()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值