如何从网络映像中获取Flutter Uint8List?

时间:2018-11-07 01:24:38

标签: image file dart flutter byte

我正在尝试将网络映像转换为文件,其中的第一部分是将其转换为Uint8List。这是我对其中的一张资产图片执行的操作...

      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);

如何使用Image.network(imageUrl.com/image)

6 个答案:

答案 0 :(得分:4)

  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);
      });
    });
  }

另请参阅https://github.com/flutter/flutter/issues/23761#issuecomment-434606683

然后您可以使用image.toByteData().buffer.asUInt8List()

另请参阅https://docs.flutter.io/flutter/dart-ui/Image/toByteData.html

答案 1 :(得分:1)

使用图像网址和response.bodyBytes来获得http响应的最简单方法似乎将包含Uint8List中的数据。

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

现在,您可以执行诸如转换为base64编码的字符串base64.encode(response.bodyBytes);

之类的操作。

答案 2 :(得分:1)

这里的答案很重要,有助于说明飞镖和颤动图像压缩/转换的工作原理。如果您想要快捷方式,可以使用此软件包https://pub.dev/packages/network_image_to_byte来简化操作。

答案 3 :(得分:0)

经过几个小时的尝试,这对我有帮助

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>");

注意:这也会将 mp4 视频转换为文件。

originally answered here

答案 4 :(得分:0)

我想出了一个不同的解决方案。希望它可以帮助某人。

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

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

答案 5 :(得分:0)

由于 http 需要 Uri,这会很有帮助: 您应该首先从 ImageAddress 中删除起始 serverAddress : 在我的情况下,我的网址中有 3001 是这样的:

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

然后:

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

这也适用于设备和网络,希望能有所帮助。

相关问题