Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'm doing it from the dartlang documentation...

var bytes = await new File('assets/placeholder.png').readAsBytes();
String base64 = CryptoUtils.bytesToBase64(bytes);

The bytes variable errors every time. How can I save the bytes of a locally saved image file?

like image 683
Charles Jr Avatar asked Nov 05 '17 18:11

Charles Jr


People also ask

How do you convert an image to bytes in flutter?

readAsBytes(); base64Image = base64Encode(imageBytes); print(base64Image);},), SizedBox(height: 30,), Image. memory(base64Decode(base64Image)), when you apply your file as a readAsBytes then you will get imagesBytes and then after you can easily convert into the base64Encode.

How do you extract data from a byte file?

File file = getSomeCorrectFile(); Uint8List bytes = file. readAsBytesSync(); return ByteData. view(bytes. buffer);


3 Answers

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');
like image 66
Hadrien Lejard Avatar answered Oct 25 '22 03:10

Hadrien Lejard


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!

like image 30
Wajid khan Avatar answered Oct 25 '22 03:10

Wajid khan


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);

like image 37
Coala Jedi Avatar answered Oct 25 '22 03:10

Coala Jedi