django - 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'
您的帮助将不胜感激。先感谢您!
解决方案
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()
推荐阅读
- python - 用二维数组写入变量会导致它改变数组的值
- mongodb - 如何在 rust 中将 MongoDB 与 r2d2 和 actix 一起使用
- c# - 具有 SQL 参数的级联组合框
- jakarta-ee - 处理不同可注入实现的最佳方法是什么?
- r - 如何将行名添加到弹性表?
- regex - 如何将列表与 Groovy 中的正则表达式匹配
- react-native - 导航问题 React native ,stack navigator
- java - Spring OAuth2 刷新令牌留下旧的访问令牌
- xml - 如何使用 spark xml 创建嵌套标签
- javascript - 将格式应用于表格中的文本 - Office-js Word