首页 > 解决方案 > Django:如何从颤动中读取使用 Dio 发送的图像

问题描述

我是 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'

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

标签: djangoflutter

解决方案


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()

推荐阅读