【问题标题】:Django: How to read an image sent using Dio from flutterDjango:如何从颤动中读取使用 Dio 发送的图像
【发布时间】:2021-06-12 18:39:00
【问题描述】:

我是 Flutter 的新手,正在尝试构建一个 Flutter 应用程序。

我想将图像从 android 设备上传到 django,对其进行处理并将结果以 json 格式发送回 Flutter,而无需将图像保存在任何地方。但是我在 django 中阅读图像时遇到了困难。但是,图像是从颤振成功发送的。

这是我使用 Dio 发送图像的颤振代码:

Future<void> _clearImage() async {
    try {
      String filename = imageFile!.path.split('/').last;
      FormData formData = FormData.fromMap({
        "image": await MultipartFile.fromFile(imageFile!.path,
            filename: filename, contentType: MediaType('image', 'jpg')),
        "type": "image/png"
      });
      Response response = await dio.post('http://IP:8000/scan/',
          data: formData,
          options: Options(
              followRedirects: false,
              // will not throw errors
              validateStatus: (status) => true,
              headers: {
                "accept": "*/*",
                "Content-Type": "multipart/form-data",
              }));
      print(response);
    } catch (e) {
      print(e);
    }
    setState(() {});
  }
}

这是我的 django 代码:

file = request.FILES['image']
print(file)
img = cv2.imread(file.read())
print(img)

我收到以下错误:

img = cv2.imread(file.read())
TypeError: Can't convert object of type 'bytes' to 'str' for 'filename'

您的帮助将不胜感激。提前谢谢!

【问题讨论】:

    标签: django flutter


    【解决方案1】:

    cv2.imread() 需要一个文件路径

    cv2.imread(path, flag)
    
    Parameters:
    path: A string representing the path of the image to be read.
    flag: It specifies the way in which image should be read. It’s default value is cv2.IMREAD_COLOR
    
    

    使用这个方法

    import numpy as np
    import cv2
    #
    #
    #
    #
    #
    #
    file = request.FILES['image']
    #
    #
    #
    nparray = np.frombuffer(file.read(), np.uint8)
    image = cv2.imdecode(nparray,  cv2.IMREAD_COLOR)
    cv2.imshow('Image',image)
    cv2.waitKey()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-15
      • 2021-08-17
      • 2021-08-26
      • 2020-10-29
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      相关资源
      最近更新 更多