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

With Flutter environment, you have to use AssetBundle if you want to access to your assets (https://flutter.io/assets-and-images/).

import 'package:flutter/services.dart' show rootBundle;


ByteData bytes = await rootBundle.load('assets/placeholder.png');

Here is an example to read file byte by byte:

import 'dart:io';

void main(List<String> arguments) {
  readFileByteByByte().then((done) {
    print('done');
  });
  print('waiting...');
  print('do something else while waiting...');
}

Future<bool> readFileByteByByte() async {
  //final fileName = 'C:\\code\\test\\file_test\\bin\\main.dart'; // use your image file name here
  final fileName = Platform.script.toFilePath(); //this will read this text file as an example
  final script = File(fileName);
  final file = await script.open(mode: FileMode.read);

  var byte;
  while (byte != -1) {
    byte = await file.readByte();
    if (byte == ';'.codeUnitAt(0)) { //check if byte is semicolon
      print(byte);
    }
  }
  await file.close();
  return (true);
}

In dart Uint8List is equal to byte[].

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

    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;
    }
    
  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!


import 'dart:convert';
import 'package:flutter/services.dart';

...

ByteData byteData = await rootBundle.load('assets/image.png');

Uint8List bytes = byteData.buffer.asUint8List();

String base64Image = base64.encode(bytes);