Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Flutter Uint8List from a Network Image?

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)

like image 688
Charles Jr Avatar asked Nov 07 '18 01:11

Charles Jr


People also ask

What is the difference between network image and image network in flutter?

They are different. NetworkImage class creates an object the provides an image from the src URL passed to it. It is not a widget and does not output an image to the screen. Image.network creates a widget that displays an image on the screen.


4 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'),
);
like image 156
lordvcs Avatar answered Oct 21 '22 05:10

lordvcs


  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

like image 30
Günter Zöchbauer Avatar answered Oct 21 '22 05:10

Günter Zöchbauer


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();
like image 7
Ujjwal Raijada Avatar answered Oct 21 '22 03:10

Ujjwal Raijada


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.

like image 1
Charles Jr Avatar answered Oct 21 '22 04:10

Charles Jr