Django: How to read an image sent using Dio from flutter

Viewed 383

I'm a newbie to Flutter and trying to build a Flutter App.

I want to upload an image from android device to django, process it and send the results back to flutter in a json format without saving the image anywhere. But I'm facing difficulty in reading image in django. However, the image is sent successfully from flutter.

Here is my flutter code for sending an image using 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(() {});
  }
}

Here is my code for django:

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

I'm getting the following error:

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

Your help will really be appreciated. Thank you in advance!

1 Answers

cv2.imread() expects a file path

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

use this method

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