python读取图片并且转码成base64

import base64

with open("grayimage.png", "rb") as img_file:
#对于图片而言read读取的结果是bytes
    b64_string = base64.b64encode(img_file.read())  
    return b64_string.decode("utf-8")

# decode is used for removing b’ from the prefix of base64 code

当然也可以使用opencv读取以后再转化

def cv2_base64(image):
    base64_str = cv2.imencode('.jpg',image)[1].tobytes()
    base64_str = base64.b64encode(base64_str)
    return base64_str.decode("utf-8")

def image_to_base64(image_filepath):
    try:
      print("ss")
      img = cv2.imread(image_filepath)
      print(img.shape)
      img_64 = cv2_base64(img)
    except Exception as e:
      print(e)
    return img_64

ref:
1.PIL&opencv&base64转化
2.convert image to base64

你可能感兴趣的:(python,python)