python对图片进行base64加密解密

 1 #!/usr/bin/env python
 2 # encoding: utf-8
 3 import os
 4 import glob
 5 from PIL import Image
 6 import base64
 7 from io import BytesIO
 8 import matplotlib.pyplot as plt
 9 
10 picture_dir=os.path.join(os.getcwd(),'*.jpg')
11 for jpgfile in glob.glob(picture_dir):
12 #encode()
13 file = open(jpgfile,'rb')
14 base64_data = base64.b64encode(file.read())
15 #decode()
16 byte_data = base64.b64decode(base64_data)
17 image_data = BytesIO(byte_data)
18 img = Image.open(image_data)
19 #show pioture
20 plt.imshow(img)
21 plt.show()

 

客户端代码:

 1 #coding=utf-8
 2 import requests,base64,json,os,shutil,cv2
 3 import numpy as np
 4 import logging
 5 logging.basicConfig(
 6     level=logging.DEBUG,
 7     format='%(asctime)s %(levelname)s: %(message)s',
 8     datefmt='%Y-%m-%d %H:%M:%S'
 9 )
10 logger = logging.getLogger(__name__)
11 bbox_http_url = 'http://10.172.32.57/get_detect_hand_bbox'
12 # 参数为cv2已read图片 可用cv2.imread(pic_path)
13 def post_for_bbox(img_im):
14     post_data = {
15         'img': base64.b64encode(cv2.imencode('.jpg',img_im)[1]).decode()
16                  }
17     r = requests.post(bbox_http_url, data=post_data)
18     if r is not None or r.text is not None:
19         return r.text
20     return None
21 def delete_hand(img_im):
22     ret_text = post_for_bbox(img_im)
23     handObj = json.loads(ret_text)
24     if handObj['status'] == 'success':
25         body = handObj['body']
26         if 'hand' not in body:
27             return
28         hands = body['hand']
29         for hand in hands:
30             cv2.rectangle(img_im, (hand[0], hand[1]), (hand[2], hand[3]), (0, 255, 0), 1)
31             # logger.info(hand)
32     # logger.info(handObj)
33     cv2.imshow('pic', img_im)
34 def main():
35     pic_path = r'E:\JD\AI\dataset\unzip\hand\10_0000736_0_0_0_0.png'
36     img_im = cv2.imread(pic_path)
37     delete_hand(img_im)
38 if __name__=='__main__':
39     main()
40     cv2.waitKey()
41     pass

 

服务端

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

 

posted on 2022-03-08 13:19  帅胡  阅读(652)  评论(0编辑  收藏  举报

导航