python中的base64使用小笑话
在使用base64的时候将本地的图片转换为base64
代码如下,代码绝对正确
import base64
def image_to_data_uri(image_path):
with open(image_path, 'rb') as image_file:
image_data = base64.b64encode(image_file.read()).decode('utf-8')
file_extension = image_path.split('.')[-1]
print(file_extension)
data_uri = f"data:image/{file_extension};base64,{image_data}"
return data_uri
image_path = 'G:/20231016015837.jpg'
data_uri = image_to_data_uri(image_path)
print(data_uri)
但是将控制台的输出结果复制到浏览器上就出问题为啥
也是十分搞笑,一度以为是python版本的问题,最后通过flask启动服务,通过掉接口的方式返回base64
from flask import Flask, jsonify, request
import base64
app = Flask(__name__)
def image_to_data_uri(image_path):
with open(image_path, 'rb') as image_file:
image_data = base64.b64encode(image_file.read()).decode('utf-8')
file_extension = image_path.split('.')[-1]
print(file_extension)
data_uri = f"data:image/{file_extension};base64,{image_data}"
return data_uri
@app.route('/getBase64', methods=['POST'])
def get_base64():
image_path = 'G:/20231016015837.jpg'
base64 = image_to_data_uri(image_path)
return jsonify({"data":base64})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
没有一点问题,原来是缺少文件被vscode的控制台给隐藏了!
哈哈哈哈