首页 > 解决方案 > 从 Flask 后端向 Flutter 前端发送和渲染多个图像

问题描述

我一直在尝试从我的烧瓶服务器发送多个图像来颤动。我已经尝试了一切,要么得到一个字节不能被 json 序列化,要么颤振在解析图像时出错。我一直在使用 Image.memory() 作为响应。奇怪的是,如果我以字节格式发送一张图像,它会按预期工作。任何帮助是极大的赞赏

@app.route('/image', methods = ['POST'])
def hola():
  with open("1.jpg", "rb") as image_file:
  encoded_string = base64.b64encode(image_file.read())
  return encoded_string

此服务器端代码按预期工作。以下是我用于 Flutter 的代码

 Future<String> uploadImage(filename, url) async {
// List<String> images;
var request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(
  await http.MultipartFile.fromPath('picture', filename),
);
request.headers.putIfAbsent('Connection', () => "Keep-Alive, keep-alive");
request.headers.putIfAbsent('max-age', () => '100000');
print(request.headers.entries);
http.Response response =
    await http.Response.fromStream(await request.send());
print("Result: ${response.statusCode}");

// print(y);
return response.body;

// return res;

}

然后我在按钮单击事件的帮助下调用此函数。像这样:

var res = await uploadImage(file.path, url);

                setState(() {
                 
                  images = res;
            
                  
                });

 Container(
          child: state == ""
              ? Text('No Image Selected')
              : Image.memory(base64.decode(images)),
        ),

以上是它呈现我发送的图像的工作示例。以下是我面临问题的地方:

服务器端:

@app.route('/send', methods= ['GET'])
def send():
  with open("1.jpg", "rb") as image_file:
   encoded_string = base64.b64encode(image_file.read())
  with open("2.jpg", "rb") as image_file:
   encoded_string2 = base64.b64encode(image_file.read())

  x = [str(encoded_string2), str(encoded_string)]
  return jsonify({'images':x})

在这里处理上面是我的颤振代码:

  var request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(
  await http.MultipartFile.fromPath('picture', filename),
);
request.headers.putIfAbsent('Connection', () => "Keep-Alive, keep-alive");
request.headers.putIfAbsent('max-age', () => '100000');
print(request.headers.entries);
http.Response response =
    await http.Response.fromStream(await request.send());
print("Result: ${response.statusCode}");
var x = jsonDecode(response.body);
var y = x['images'];
var z = y[0];
images = z;

为了渲染图像,容器代码保持不变。我收到此错误:

The following _Exception was thrown resolving an image codec:
Exception: Invalid image data

或者我得到:

Unexpected character at _

我尝试以不同的方式解析,例如:

var x = jsonDecode(response.body);
var y = x['images'];

var z = utf8.encode(y[0]);
images = base64Encode(x[0]);

或这个:

 var x = jsonDecode(response.body);
var y = x['images'];

var z = base64Decode(y[0]);
images = z;

但没有任何效果

标签: pythonflutterapiflask

解决方案


如果您尝试在响应中返回多个图像二进制文件,我假设看起来像

{ "image1":"content of image one bytes", "image2":"content of image two bytes" }

正如您发现的那样,问题在于二进制内容不能天真地编码为 json

通常会做的是将其转换为 base64

{"image1":base64.b64encode(open("my.png","rb").read()),"image2":open(...)}

大多数东西都可以渲染base64(不完全确定专门针对颤振图像(但肯定针对html中的标签)

<img src="data:image/png;base64,<BASE64 encoded data>" />

如果不是,您总是可以使用 base64decode 取回字节(flutter 几乎可以肯定它的一个库中有)


推荐阅读