How to Convert Image to Base64 Encoding in Flutter/Dart

In this example, we are going to show you how to convert image path to File, Uint8List bytes, and encode it to base64 or decode back base64 string to bytes. See the example below:

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
String imagepath = " /data/user/img.jpg"; 
//image path, you can get it with image_picker package

File imagefile = File(imagepath); //convert Path to File
Uint8List imagebytes = await imagefile.readAsBytes(); //convert to bytes
String base64string = base64.encode(imagebytes); //convert bytes to base64 string
print(base64string); 

/* Output:
  /9j/4Q0nRXhpZgAATU0AKgAAAAgAFAIgAAQAAAABAAAAAAEAAAQAAAABAAAJ3
  wIhAAQAAAABAAAAAAEBAAQAAAABAAAJ5gIiAAQAAAABAAAAAAIjAAQAAAABAAA
  AAAIkAAQAAAABAAAAAAIlAAIAAAAgAAAA/gEoAA ... long string output
*/ 

import 'dart:convert';
import 'dart:typed_data';
Uint8List decodedbytes = base64.decode(base64string);
//decode base64 stirng to bytes

For more information about decoding/encoding files: How to Encode/Decode Path, File, Bytes, and Base64 in Dart/Flutter

In this example, we are going to make an image picker and convert it to a base64 string. To make an image picker, we have used image_picker Flutter package, add this package to your project by adding the following lines in pubspec.yaml file.

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return MaterialApp(
         home: Home()
      );
  }
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  final ImagePicker imgpicker = ImagePicker();
  String imagepath = "";
  
  openImage() async {
    try {
        var pickedFile = await imgpicker.pickImage(source: ImageSource.gallery);
        //you can use ImageCourse.camera for Camera capture
        if(pickedFile != null){
              imagepath = pickedFile.path;
              print(imagepath); 
              //output /data/user/0/com.example.testapp/cache/image_picker7973898508152261600.jpg

              File imagefile = File(imagepath); //convert Path to File
              Uint8List imagebytes = await imagefile.readAsBytes(); //convert to bytes
              String base64string = base64.encode(imagebytes); //convert bytes to base64 string
              print(base64string); 
              /* Output:
              /9j/4Q0nRXhpZgAATU0AKgAAAAgAFAIgAAQAAAABAAAAAAEAAAQAAAABAAAJ3
              wIhAAQAAAABAAAAAAEBAAQAAAABAAAJ5gIiAAQAAAABAAAAAAIjAAQAAAABAAA
              AAAIkAAQAAAABAAAAAAIlAAIAAAAgAAAA/gEoAA ... long string output
              */ 

              Uint8List decodedbytes = base64.decode(base64string);
              //decode base64 stirng to bytes

              setState(() {
              
              });
        }else{
           print("No image is selected.");
        }
    }catch (e) {
        print("error while picking file.");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Image to base64 Encoding"),
            backgroundColor: Colors.redAccent,
         ),

         body: Container(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children: [

                  imagepath != ""?Image.file(File(imagepath)):
                    Container( 
                      child: Text("No Image selected."),
                    ),

                    //open button ----------------
                    ElevatedButton(
                      onPressed: (){
                          openImage();
                      }, 
                      child: Text("Open Image")
                    ),
               ]
             ),
         )

    );
  } 
}

I/flutter (13692): /data/user/0/com.example.testapp/cache/image_picker3914322741947862186.jpg

I/flutter (13692): /9j/4Q0nRXhpZgAATU0AKgAAAAgAFAIgAAQAAAABAAAAAAEAAAQAAAABAAAJ3wIhAAQAAAABAA
AAAAEBAAQAAAABAAAHuAIiAAQAAAABAAAAAAIjAAQAAAABAAAAAAIkAAQAAAABAAAAAAIlAAIAAAAgAAAA/gEo
AAMAAAABAAIAAAEOAAIAAAAgAAABHgEPAAIAAAAgAAABPgEQAAIAAAAgAAABXgExAAIAAAAgAAABfgEyAAIAAA
AUAAABngESAAMAAAABAAEAAAITAAMAAAABAAIAAIdpAAQAAAABAAABwoglAAQAAAABAAALtAEaAAUAAAABAA
ABsgEbAAUAAAABAAABugAADM0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWGlhb21pAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNMjAwM
0oxNVNDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE1lZGlhVGVrIENhbWVyYSBBcHBsaWNhdGlvbgAAAAAAMjAyM
ToxMjowOSAxMTowNzo1NQAAAABIAAAAAQAAAEgAAAABAB6aqgABAAAIAAAAAzCIJwADAAAAAQD0AACIIgADAA
AAAQAAAACCnQAFAAAAAQAACzCCmgAFAAAAAQAACziIlQADAAAAAQAAAACSkgACAAAAAzkzAACSkQACAAAAA
zkzAACSkAACAAAAAzkzAACSCgAFAAAAAQAAC0CSCQADAAAAAQAAAACIiQACAAAACQAAC0iSCAADAAAAAQD/A
ACSBwADAAAAAQACAACkBgADAAAAAQAAAACgBQAEAAAAAQAAC5akBQADAAAAAQAcAACQBAACAAAAFAAAC1
GSBAAKAAAAAQAAC2WkBAAFAAAAAQAAC22gAwAEAAAAAQAAD6CkAwADAAAAAQAAAACQAwACAAAAFAAAC3
WgAgAEAAAAAQAAC7ikAgADAAAAAQAAAACRAQA

In this way, you can encode or decode Image to base64 string or vice versa in Dart/Flutter App.

No any Comments on this Article


Please Wait...