我如何解析颤振中响应正文中的图像

问题描述 投票:0回答:1

我的应用程序由 python 服务器和 Flutter 客户端组成。我打算将图像列表从 flutter 客户端发送到 python 服务器,对它们进行一些操作(例如翻转、调整大小),然后立即将处理后的图像发送回。我的代码如下:

服务器

from fastapi import FastAPI, UploadFile
from typing_extensions import List
from PIL import Image
import io

app = FastAPI()

@app.post('/process')
async def upload_images(files: List[UploadFile]):
    imgs = []
    for f in files:
        contents = await f.read()
        image = Image.open(io.BytesIO(contents))
        # do something with image
        # ...
        imgs.append(image)
    return imgs


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

客户

import 'dart:io';
import 'package:http/http.dart';

void main() async {
  const String url = "http://localhost:8000/process";
  var request = MultipartRequest("POST", Uri.parse(url));

  var image = File('image.jpg');
  request.files.add(await MultipartFile.fromPath('files',image.path));
  request.files.add(await MultipartFile.fromPath('files',image.path));

  final response = await request.send();
  var responseBytes = await response.stream.toBytes();
  exit(0);
}

通过上面的代码,我成功地向客户端发送了图像列表,但我不知道如何解析返回的结果? 有没有办法将图像内容发送回来,并将它们存储到 Flutter 中的File列表中(以便我可以保存或显示它们)?

上面提到的

responseBytes是我得到过的最远的东西。我尝试了多种方法,但都不起作用。

flutter image http response fastapi
1个回答
0
投票
您可以通过不同的方式存储图像文件。

动态列表其中图像列表临时存储在变量中。这种方法的限制是,这非常占用内存,特别是当您存储多个图像或大量图像数据时,但如果不需要大缓存,这比使用文件非常高效和快速,但图像会丢失当您关闭应用程序时。

使用本地存储。 您可以使用库将图像存储在本地,然后在需要时打开它们。这需要管理文件管理的 CRUD 功能。

使用 Hive 等库 这可能是我们说话时我最喜欢的方法。 Hive 允许键值存储并使您无需知道确切的位置或文件名,您只需创建一个
key: value

 列表并将其存储在 Hive 框中。文件将保存在本地,可以随时访问。

© www.soinside.com 2019 - 2024. All rights reserved.