4

I've an array of string containing 5 image urls. I'm looking out for a way to fetch the image from url, then encode the image as base64 string, and finally insert that to another array.

The solution should work for both mobile and web in flutter. I was digging around for the solution and got some tricks using File.readAsBytes, Image.toBase64String, etc., but none of them worked on my side.

iAkshay
  • 1,143
  • 1
  • 13
  • 35
  • 1
    might be helpful https://stackoverflow.com/questions/50036393/how-to-convert-an-image-to-base64-image-in-flutter – Aamil Silawat Mar 06 '20 at 13:54
  • @AR Thanks but I've already visited the link you provide. The solution proposed there isn't working as I mentioned in the question. – iAkshay Mar 06 '20 at 14:06

1 Answers1

12

Finally I found the solution using http package

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

Future<String> networkImageToBase64(String imageUrl) async {
    http.Response response = await http.get(imageUrl);
    final bytes = response?.bodyBytes;
    return (bytes != null ? base64Encode(bytes) : null);
}

Example:

final imgBase64Str = await networkImageToBase64('IMAGE_URL');
print(imgBase64Str);

This is working perfectly for both mobile and web.

iAkshay
  • 1,143
  • 1
  • 13
  • 35