【问题标题】:Convert a UInt8List to Image in flutter/dart-ui在 Flutter/dart-ui 中将 UInt8List 转换为 Image
【发布时间】:2019-05-30 12:25:42
【问题描述】:

我有这种情况,我必须从这样的图像中获取 UInt8List:

List stuff = image.toByteData().buffer.asUInt8List()

进行一些操作并返回Image

我尝试了以下方法:

List stuff = image.toByteData().buffer.asUInt8List()
ui.decodeImageFromList(stuff, (image){
  // do stuff with image
});

但我不断收到此异常:

E/flutter (10201): [ERROR:flutter/lib/ui/painting/codec.cc(97)] Failed decoding image. Data is either invalid, or it is encoded using an unsupported format.
E/flutter (10201): [ERROR:flutter/shell/common/shell.cc(186)] Dart Error: Unhandled exception:
...

请注意,即使列表中没有任何更改,也会引发异常。如何使列表具有可编码格式?

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    ui.Image 可以将自己转换为 RGBA 位图(或 PNG),但不能将自己从位图转换回来。 (原因是没有任何方法可以告诉图像编解码器颜色深度、几何形状等。)解决方案是在位图的前面添加一个 BMP 文件头,您可以在其中描述那些丢失的东西,然后将其传递给instantiateImageCodec。请参阅this answer,但请注意,在这种情况下,所讨论的位图有一个奇怪的打包颜色图。在您使用 32 位 RGBA 的情况下,标头会更简单。

    【讨论】:

    • 得到这个答案后,我开始着手做一些事情来让这件事变得更容易。我正在将 Uint8List 转换为 Image with Bitmap,这是我制作的一个包。谢谢。 github.com/renancaraujo/bitmap
    【解决方案2】:

    您可以使用 MemoryImage 类将 Uint8List 转换为图像。

    var _image = MemoryImage(image);

    你可以找到更多关于这个课程的细节here

    【讨论】:

      【解决方案3】:

      您可以使用下面给出的内存图像,用于直接字节渲染

      child: Image.memory(Uint8List bytes);
      

      【讨论】:

      • 这不适用于从 ui.Image 实例生成的 Uint8List
      【解决方案4】:

      使用这个。

      static Future<ui.Image> bytesToImage(Uint8List imgBytes) async{
          ui.Codec codec = await ui.instantiateImageCodec(imgBytes);
          ui.FrameInfo frame = await codec.getNextFrame();
          return frame.image;
        }
      

      【讨论】:

      • 需要导入import 'dart:ui' as ui;
      【解决方案5】:

      这是一个经过测试的代码。

          final directory = await getApplicationDocumentsDirectory();
          final pathOfImage = await File('${directory.path}/legendary.png').create();
          final Uint8List bytes = stuff.buffer.asUint8List();
          await pathOfImage.writeAsBytes(bytes);
      

      最终的 Uint8List 字节 = stuff.buffer.asUint8List();

      这里,stuff指的是应该转换成图片的Uint8List。

      【讨论】:

        【解决方案6】:

        这个方法对我有用,从 stackoverflow here 上类似问题的另一个答案中获得了参考

        Future<ui.Image> loadImage(Uint8List img) async {
            final Completer<ui.Image> completer = Completer();
            ui.decodeImageFromList(img, (ui.Image img) {
              return completer.complete(img);
            });
            return completer.future;
          }
        

        【讨论】:

          猜你喜欢
          • 2020-08-25
          • 2022-08-18
          • 2020-07-25
          • 2020-03-16
          • 2021-07-26
          • 2019-12-28
          • 2020-05-20
          • 2018-12-13
          • 2022-10-05
          相关资源
          最近更新 更多