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

Published by Abhay Rastogi on

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


1 Comment

Resolved: How to print QR Image in thermal printer using flutter - Daily Developer Blog · 25th November 2022 at 5:52 am

[…] have also tried this it’s printed the string value of Image not image itself, is there anyway I can print image […]

Leave a Reply

Avatar placeholder

Your email address will not be published.