Save Image From ImagePicker Locally as a Memory(cache)

Issue

I want to save an Image from ImagePicker as a Memory but error Occured . Can you Please help me with this function and if another function needed to load image please Mentioned it below.

Uint8List? memoryImage;
  Future getImage() async {
    
     final picker = ImagePicker();
          final image = await picker.getImage(source: ImageSource.camera);

          if (image == null) return;
          final Directory directory = await getApplicationDocumentsDirectory();
          final path=directory.path;
          final Filename=basename(image.path);
          File file = File('$directory/$Filename.jpg');
        final bytes = await file.readAsBytes();
        final byte1=  file.writeAsBytes(bytes);
        

    setState(() {
      memoryImage = byte1 as Uint8List?;
    });
   
  }

Solution

With this line you can write image bytes as a file.

File imageFile = await File(fileSavePath).writeAsBytes(imageBytes);

To access the Uint8List from the file you need to use

Uint8List memoryImage = File(imagePath).readAsBytesSync();

Or

Uint8List memoryImage = await File(imagePath).readAsBytes();

here the problem in your code is you are assigning file to a Uint8List. That’s the error I guess

Answered By – Mr.Paul

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *