Converting Image FlutterWebImagePicker Output to File

Viewed 754

I'm using Flutter web for a webapp and having trouble converting an image from the image picker to a file in order to upload it to my server. I display the image in Image.file(xxx) but I get the error:

Error while trying to load an asset: FormatException: Illegal scheme character (at character 6) Image(image:%20MemoryImage(Uint8List%234267a,%20scale:%201),%20frameBuilder...

Here is the code I'm trying:

Future getImage(bool isCamera) async {

    Image image;

    if (isCamera) {
      image = await FlutterWebImagePicker.getImage;
    } else {
    }

     var bytes = await rootBundle.load('$image');
    String tempPath = (await getTemporaryDirectory()).path;
    File file = File('$tempPath/profile.png');

    await file.writeAsBytes(
        bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));


    setState(() {
      currentSelfie = file;
      _accDetails['customer_selfie'] = currentSelfie;
    });
  }

Thanks in advance

2 Answers

I've tested this package and was very happy with the result imagePickerWebit returns 3 different types it can be in the form of Image(widget for preview), byte, File(upload)

then you can use this to get the values

 html.File _cloudFile;
 var _fileBytes;
 Image _imageWidget;
 
 Future<void> getMultipleImageInfos() async {
    var mediaData = await ImagePickerWeb.getImageInfo;
    String mimeType = mime(Path.basename(mediaData.fileName));
    html.File mediaFile =
        new html.File(mediaData.data, mediaData.fileName, {'type': mimeType});

    if (mediaFile != null) {
      setState(() {
        _cloudFile = mediaFile;
        _fileBytes = mediaData.data;
        _imageWidget = Image.memory(mediaData.data);
      });
    }

I havent used the plugin although your code has 2 issues. One is the if statement and the second one is using Rootbundle. If you are picking from the filesystem, my assumption isCamera would be false. You have not added any logic for the falsy condition.

 if (isCamera) {// This would be true if the source was camera
  image = await FlutterWebImagePicker.getImage;
 } else {

 }

Additionally,

var bytes = await rootBundle.load('$image');

From the flutter documentation, rootbundle contains the resources that were packaged with the application when it was built. Those are assets that you define in your pubspec. yaml. You are selecting an image at runtime hence its not bundled as an asset.

Since the package appears to return an image object, use the toByteData method on the image i.e

image = await FlutterWebImagePicker.getImage;
await image.toByteData();//This method has some parameters. Look into them
Related