python中base64加解密图片进行post传输

在post中传输图片时,通过对图片进行base64加密成字符串传输,在服务端在base64解码为图片在一些场景中往往更简单、高效。

客户端代码:

#coding=utf-8
import requests,base64,json,os,shutil,cv2
import numpy as np
import logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
bbox_http_url = 'http://10.172.32.57/get_detect_hand_bbox'
# 参数为cv2已read图片 可用cv2.imread(pic_path)
def post_for_bbox(img_im):
    post_data = {
        'img': base64.b64encode(cv2.imencode('.jpg',img_im)[1]).decode()
                 }
    r = requests.post(bbox_http_url, data=post_data)
    if r is not None or r.text is not None:
        return r.text
    return None
def delete_hand(img_im):
    ret_text = post_for_bbox(img_im)
    handObj = json.loads(ret_text)
    if handObj['status'] == 'success':
        body = handObj['body']
        if 'hand' not in body:
            return
        hands = body['hand']
        for hand in hands:
            cv2.rectangle(img_im, (hand[0], hand[1]), (hand[2], hand[3]), (0, 255, 0), 1)
            # logger.info(hand)
    # logger.info(handObj)
    cv2.imshow('pic', img_im)
def main():
    pic_path = r'E:\JD\AI\dataset\unzip\hand\10_0000736_0_0_0_0.png'
    img_im = cv2.imread(pic_path)
    delete_hand(img_im)
if __name__=='__main__':
    main()
    cv2.waitKey()
    pass

服务端解码关键代码:

def base64str_to_im(img_data_str):
    img_byte = base64.b64decode(img_data_str)
    img_np_arr = np.fromstring(img_byte,np.uint8)
    im = cv2.imdecode(img_np_arr,cv2.IMREAD_COLOR)
    return im

猜你喜欢

转载自blog.csdn.net/otengyue/article/details/79278816