Andrey Molochko
Andrey Molochko

Reputation: 768

How to get a Uint8List from a Network image by url in Flutter?

I have the network url of image and I need to get Uint8List. How can I convert it? I check answers in like question, but those ways don't work. How to get a Flutter Uint8List from a Network Image?

Upvotes: 7

Views: 13047

Answers (5)

Cristhian Apolo
Cristhian Apolo

Reputation: 11

I'm having the same problem in Flutter web, I had to use the extended_image library, and I found inside your example that has a method that allows you to convert an ImageProvider to Bytes.

https://github.com/fluttercandies/extended_image/blob/master/example/lib/pages/simple/image_editor_demo.dart.

/// it may be failed, due to Cross-domain
Future<Uint8List> _loadNetwork(ExtendedNetworkImageProvider key) async {
  try {
    final Response response = await HttpClientHelper.get(Uri.parse(key.url),
        headers: key.headers,
        timeLimit: key.timeLimit,
        timeRetry: key.timeRetry,
        retries: key.retries,
        cancelToken: key.cancelToken);
    return response.bodyBytes;
  } on OperationCanceledError catch (_) {
    print('User cancel request ${key.url}.');
    return Future<Uint8List>.error(
        StateError('User cancel request ${key.url}.'));
  } catch (e) {
    return Future<Uint8List>.error(StateError('failed load ${key.url}. \n $e'));
  }
}

Upvotes: 0

Sha-agi
Sha-agi

Reputation: 304

This works on me (using flutter web) with a library file_saver.

Uri uri = Uri.parse(url);

Uint8List bytes = await readBytes(uri);
await FileSaver.instance.saveFile(filename, bytes, 'jpg',
    mimeType: MimeType.JPEG); // specify your vars

Upvotes: 1

S&#233;rgio Ildefonso
S&#233;rgio Ildefonso

Reputation: 72

this did the trick for me:

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

//Get the image from the URL and then convert it to Uint8List
Uint8List bytes = (await NetworkAssetBundle(Uri.parse('https://some_image_url.png'))
            .load('https://some_image_url.png'))
            .buffer
            .asUint8List();

Upvotes: 3

kaya
kaya

Reputation: 754

Try this:

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

Upvotes: 14

Andrey Molochko
Andrey Molochko

Reputation: 768

Uint8List yourVar;
final DecoderCallback callback = (Uint8List bytes, {int cacheWidth, int cacheHeight}) {
        yourVar = bytes.buffer.asUint8List();
        return instantiateImageCodec(bytes, targetWidth: cacheWidth, targetHeight: cacheHeight);
      };
ImageProvider provider = NetworkImage(yourImageUrl);
    provider.obtainKey(createLocalImageConfiguration(context)).then((key) {
      provider.load(key, callback);
    });

Upvotes: 6

Related Questions