Flutter/Dart: how to convert image to base64 string?

Published by Abhay Rastogi on

flutter/ dart image to base64

In this, we will see how we can convert image to base64 string and string to image using base64encoding and base64decoding. We will see Url image to base64 and File image to base64.

Flutter Convert Url Image to base64 string

Base64 Encode

For Converting Http or URL image to base64 in a flutter. we have to first install the http: plugin in pubspec.yaml underneath the dependencies.

First step is to Encode the image into base64 String.

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

http.Response response = await http.get(
   'https://cdn.pixabay.com/photo/2020/09/23/14/38/woman-5596173_960_720.jpg',
      );

_base64 = base64Encode(response.bodyBytes);

print(_base64); 

Base64 Decode

After Encoding now it’s time to decode the base64 string into image.

 _base64 = base64Decode(response.bodyBytes);
image.memory(_base64);

Flutter Convert File Image to base64 string

Base64 Encode

First step is to Encode the image into base64 String.

 var imageFilePath = await picker.getImage(source: ImageSource.gallery);
 
 final bytes = ImageFilePath.readAsBytesSync();
 String _img64 = base64Encode(bytes);

Base64 Decode

After Encoding the file image now it’s time to decode the base64 string into image.

_img64 = base64Decode(response.bodyBytes);
image.memory(_img64);

0 Comments

Leave a Reply

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