How to get a Flutter Uint8List from a Network Image?

Viewed 32817

I'm trying to convert a network image into a file and the first part of that is to convert it into a Uint8List. Here is how I'm doing this with 1 of my asset images...

      final ByteData bytes = await rootBundle.load('assests/logo');
      final Uint8List list = bytes.buffer.asUint8List();

      final tempDir = await getTemporaryDirectory();
      final file = await new File('${tempDir.path}/image.jpg').create();
      file.writeAsBytesSync(list);

How can I do this with Image.network(imageUrl.com/image)

6 Answers

The simplest way seeems to get the http response using the image url and response.bodyBytes would contain the data in Uint8List.

http.Response response = await http.get(
    'https://flutter.io/images/flutter-mark-square-100.png',
);   
response.bodyBytes //Uint8List

Now you can do things like converting to base64 encoded string base64.encode(response.bodyBytes);
Update: With newer version of http, you need to add Uri.parse()
Eg.

http.Response response = await http.get(
    Uri.parse('https://flutter.io/images/flutter-mark-square-100.png'),
);
  void initState() {
    super.initState();
    var sunImage = new NetworkImage(
        "https://resources.ninghao.org/images/childhood-in-a-picture.jpg");
    sunImage.obtainKey(new ImageConfiguration()).then((val) {
      var load = sunImage.load(val);
      load.addListener((listener, err) async {
        setState(() => image = listener);
      });
    });
  }

See also https://github.com/flutter/flutter/issues/23761#issuecomment-434606683

Then you can use image.toByteData().buffer.asUInt8List()

See also https://docs.flutter.io/flutter/dart-ui/Image/toByteData.html

I figured out a different solution. Hope it helps someone.

import 'dart:typed_data';
import 'package:flutter/services.dart';

Uint8List bytes = (await NetworkAssetBundle(Uri.parse(imageUrl))
            .load(imageUrl))
            .buffer
            .asUint8List();

The answers here are relevant and help explain how dart and flutter image compression/conversion works. If you would like a shortcut, there is this package https://pub.dev/packages/network_image_to_byte that makes it really easy.

After trying for hours this is what helped me

import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';

Future<File> getFileFromNetworkImage(String imageUrl) async {
  var response = await http.get(imageUrl);
  final documentDirectory = await getApplicationDocumentsDirectory();
  String fileName = DateTime.now().millisecondsSinceEpoch.toString();
  File file = File(path.join(documentDirectory.path, '$fileName.png'));
  file.writeAsBytes(response.bodyBytes);
  return file;
}

final file = await getFileFromNetworkImage("<your network image Url here>");

Note: this also converts mp4 videos to a File.

originally answered here

As http needs Uri this would be helpful: you should remove the begining serverAddress from your ImageAddress first : something like this in my case that I have 3001 in my url:

    String serverAddress = 'myAddress.com:3001';
    int indexOf3001 = imageAddress.indexOf('3001');
    String trimmedImageAddress= imageAddress.substring(indexOf3001 + 4);

then :

    var imageUrl = Uri.https(serverAddress, trimmedImageAddress);
    final http.Response responseData = await http.get(imageUrl);
    Uint8List imageBytes = responseData.bodyBytes;

this works on device and web too, hope it can help.

Related