图片和base64编码互转
import base64
import cv2# 将图片base64字符串生成图片文件.
def base64_to_img(base64_code,save_img_path):"""根据base64生成图片.:param base64_code: 图片的base64文件:param save_img_path: 生成的图片路径:returns: None"""try:imgdata = base64.b64decode(base64_code)with open(save_img_path, mode="wb") as f:f.write(imgdata)except Exception as ex:print(ex)# 将图片文件转换成base64字符串
def img_to_base64(img_file):'''将图片转换成base64字符串:param img_file:图片文件:return:base64字符串'''try:with open(img_file, 'rb') as f:img_data = f.read()uri = base64.b64encode(img_data)return uri.decode('utf-8')except Exception as ex:print(ex)# 将图片文件转换成base64字符串(cv2读取)
def img_to_base64_bycv2(img_file):'''将图片转换成base64字符串:param img_file:图片文件:return:base64字符串'''try:im = cv2.imread(img_file)data = cv2.imencode('.png', im)[1]str_base64 = base64.b64encode(data.tobytes()).decode('utf8')return str_base64except Exception as ex:print(ex)