参考
Base64 编码说明:https://c.runoob.com/front-end/693/
转换成base64后需要解码避免报错
import base64
with open('./aa.jpg', 'rb') as f:
qrcode = base64.b64encode(f.read()).decode()
"""
#The following is wrong, when json.dumps is run, it will raise error "TypeError: Object of type 'bytes' is not JSON serializable"
"""
#qrcode = base64.b64encode(f.read())
完整流程,本地文件先编码后解码
ENCODING = 'utf-8' # 指定编码形式
SCRIPT_NAME, IMAGE_NAME, JSON_NAME = argv # 获得文件名参数
# 读取二进制图片,获得原始字节码,注意 'rb'
with open(IMAGE_NAME, 'rb') as jpg_file:
byte_content = jpg_file.read()
# 把原始字节码编码成 base64 字节码
base64_bytes = b64encode(byte_content)
# 将 base64 字节码解码成 utf-8 格式的字符串
base64_string = base64_bytes.decode(ENCODING)