1

I'm sharing a picture that I've taken previously with the camera using image_picker. It works fine on the emulator but not on my device:

onPressed: () async {
  ByteData image = await rootBundle.load(team.avatar.path);
  ...
},

This is the error with the path:

Unable to load asset: /storage/emulated/0/Android/data/drodriguez.apps.Words/files/Pictures/scaled_2eccad3d-382e-462e-b124-b8fa06a2a32b791445736175256137.jpg

The image is being shown without errors so the path is 100% correct:

Image.file(
  _orderedTeams[index].avatar,
  fit: BoxFit.cover,
  height: 92.0,
  width: 92.0,
)

Do I need to add something else maybe on the pubspec.yml?

Dani
  • 3,128
  • 2
  • 43
  • 91

1 Answers1

3

You can't use the rootBundle to access files on the phone. The rootBundle (as said in its docs) only works for files packaged with the application when was built (probably saved on assets, declared on pubspec, etc).

If you want to load an image from the phone, this maybe help.


ANSWER

This function can read a filePath and return a Uint8List (a byteArray):

Future<Uint8List> _readFileByte(String filePath) async {
    Uri myUri = Uri.parse(filePath);
    File audioFile = new File.fromUri(myUri);
    Uint8List bytes;
    await audioFile.readAsBytes().then((value) {
    bytes = Uint8List.fromList(value); 
    print('reading of bytes is completed');
  }).catchError((onError) {
      print('Exception Error while reading audio from path:' +
      onError.toString());
  });
  return bytes;
}

And, to get a ByteData just:

var path = 'Some path to an image';
var byteArray = _readFileByte(path);
ByteData data = ByteData.view(byteArray.buffer);

(The answer is based on this)

Community
  • 1
  • 1
Ademir Villena Zevallos
  • 1,579
  • 1
  • 13
  • 20
  • Thanks for the clarification. I don't want to load the image, that's working already. I want to share it – Dani Jan 08 '20 at 15:09
  • Do you want an image that is on the phone (lets say, a photo taken by the camera), be converted to a `ByteData`? – Ademir Villena Zevallos Jan 08 '20 at 15:11
  • 1
    This answer [here](https://stackoverflow.com/a/57110584/7120472) (not the accepted) is what you want. Read the image from the path and return a byte array. (After that you can convert the byte array to a `ByteData` with `ByteData data = ByteData.view(byteArray.buffer);`) – Ademir Villena Zevallos Jan 08 '20 at 15:19
  • Wow, that works perfectly. Feel free to add it on a different answer and I'll approve it as valid one. Muchas gracias! – Dani Jan 08 '20 at 15:28