Fetch image from URL and convert it to base64 string - Flutter

4,592

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.

Share:
4,592
iAkshay
Author by

iAkshay

Passionate about bringing an ideas into mobile apps :)

Updated on December 18, 2022

Comments

  • iAkshay
    iAkshay over 1 year

    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.

    • Aamil Silawat
      Aamil Silawat about 4 years
    • iAkshay
      iAkshay about 4 years
      @AR Thanks but I've already visited the link you provide. The solution proposed there isn't working as I mentioned in the question.
  • Thiago Silva
    Thiago Silva over 3 years
    It works but then crashs with an error 36 - File name is too long.