Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 426
iAkshay Avatar asked Oct 23 '25 14:10

iAkshay


1 Answers

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.

like image 87
iAkshay Avatar answered Oct 26 '25 05:10

iAkshay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!