dart-flutter-encode-decode-image-base64-feature-image

Dart/Flutter – Encode/Decode Image to/from Base64 String

In this tutorial, I will show you how to encode Image file to Base64 & decode Base64 String to Image in Dart/Flutter using dart:convert library.

Overview

1. Encode Image to Base64

There are two steps to encode an Image file to Base64 String:

  • convert our Image file to bytes with the help of dart:io library.
  • import 'dart:io' as Io;
    
    final bytes = await Io.File(image).readAsBytes();
    // or
    final bytes = Io.File(image).readAsBytesSync();
    
  • use dart:convert library base64Encode() function to encode bytes to Base64.
  • It is the shorthand for base64.encode().

    String base64Encode(List<int> bytes) => base64.encode(bytes);
    

2. Decode Base64 to Image

To convert a Base64 String into Image, we need to do 2 steps:

  • use base64Decode() function which is shorthand for base64.decode() to decode Base64 to bytes.
  • Uint8List base64Decode(String source) => base64.decode(source);
    
  • write the bytes to Image file using dart:io writeAsBytes() or writeAsBytesSync().
  • import 'dart:io' as Io;
    
    var file = Io.File(image);
    
    await file.writeAsBytes(bytes);
    // or
    file.writeAsBytesSync(bytes);
    

Practice

1. Encode Image to Base64

import 'dart:io' as Io;
import 'dart:convert';

main() {
  final bytes = Io.File('bezkoder.png').readAsBytesSync();

  String img64 = base64Encode(bytes);
  print(img64.substring(0, 100));  
}

Output:

iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAMAAABIw9uxAAADAFBMVEX///8PDxEHBwkODhAQEBIFBQcTExUGBggRERMSEhQICAoa

2. Decode Base64 String to Image

import 'dart:io' as Io;
import 'dart:convert';

main() {
  // img64 = iVBORw0KGgoAAAANSUhEUgAAB...
  final decodedBytes = base64Decode(img64);

  var file = Io.File("decodedBezkoder.png");
  file.writeAsBytesSync(decodedBytes);
}

Check decodedBezkoder.png, you can see that it is the same as bezkoder.png.

Further Reading

Leave a Reply

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