我正在尝试使用Flask构建一个简单的API,现在我想在其中读取一些gif图片。我需要做什么才能使其可序列化为JSON?
下面是我的简单代码:
def getfile(filename):
file = request.files['file']
return file.read()
@namespace.route('/get_image')
class Getpicture(DecoratedResource):
@staticmethod
def get():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
file = getfile(filename)
return jsonify(file, mimetype='image/gif') 结果如下:
{ "message":“浏览器(或代理)发送了此服务器无法理解的请求。”}
发布于 2020-01-10 18:04:01
一种可能的解决方案是将图像编码为base64字符串,然后将其提供给json,这样您只需传递字符串,而不必尝试将图像转换为json
import base64
with open("yourfile.ext", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())https://stackoverflow.com/questions/55265779
复制相似问题