How to read bytes of a local image file in Dart/Flutter?

前端 未结 3 784
时光说笑
时光说笑 2021-01-11 19:42

I would like to use a placeholder image file that I\'ve added to my code as \"assets/placeholder.png\", but I\'m getting a File not found error. This is how I\

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-11 19:54

    In dart Uint8List is equal to byte[].

    1. Create one function and pass file path, It will return Bytes.

      Future _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;
      }
      
    2. Now call the function in to get bytes of file.

      try{
        Uint8List audioByte;
        String myPath= 'MyPath/abc.png';
        _readFileByte(myPath).then((bytesData) {
          audioByte = bytesData;
        //do your task here 
        });
      } catch (e) {
         // if path invalid or not able to read
        print(e);
      }
      
    3. If you want base64String then use below code:

      String audioString = base64.encode(audioByte);

    for base64 import 'dart:convert';

    I hope it will help!

提交回复
热议问题