【问题标题】:Flutter: Convert Base64 String to Image (Type File Variable)Flutter:将 Base64 字符串转换为图像(类型文件变量)
【发布时间】:2019-11-12 18:19:27
【问题描述】:

使用 Flutter Package image_picker 拍摄照片并保存为“文件”类型的变量。 这些图像可以用 Flutter 查看。 来自 BASE64 格式的 JSON 字符串中的照片应格式化为此数据类型,以便能够显示它们。 有谁知道这是怎么回事?

可以使用 Flutter 直接显示 BASE64 图像。 问题是渲染时会出现“闪烁”效果,因为每次用户输入时都会重新加载照片。 该框架在 BASE64 图像中似乎没有注意到它始终是同一张照片。 对于文件类型的照片,不会出现此问题。

因此我不推荐直接渲染 BASE64 字符串。 所以我想应用转换。

有没有人解决如何将BASE64字符串转换为“文件”类型的变量?

    var picturesTaken = <File>[];

    Widget _showFoto(int currentFoto) {
      return Padding(
          padding: const EdgeInsets.only(bottom: 10.0),
          child: Container(
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: Center(
                child: Column(
                  children: <Widget>[
                    Image.file(picturesTaken[currentFoto])
                  ],
                ),
              ),
            ),
          )
      );
    }

【问题讨论】:

  • 试试 Base64Decoder().convert(imgBase64Str)

标签: image flutter package


【解决方案1】:

您的 base64 字符串不应在前缀中包含“data:image/jpg;base64,”等部分

List<int> imageBytes = _image.readAsBytesSync();
String imageB64 = base64Encode(imageBytes);

在用户界面中显示

Image.memory(
   img,
   width: 85,
   height: 85,
   fit: BoxFit.cover,
)

【讨论】:

  • 感谢您的回答。原则上,这是可行的。不幸的是,在这个变体中,你会看到用户的“拍打”效果。有没有办法将 Uint8List 类型的变量转换为 File 类型的变量?
【解决方案2】:

根据您的回答,我找到了解决方案:

    Image.memory(
      img,
      width: 85,
      height: 85,
      fit: BoxFit.cover,
      gaplessPlayback: true
    )  

【讨论】:

    【解决方案3】:
    import 'dart:convert';
    import 'dart:typed_data';
    
    String _base64;   
    Uint8List bytes = BASE64.decode(_base64);
    Image.memory(bytes)
    

    (或)

    Image imageFromBase64String(String base64String) {
     return Image.memory(base64Decode(base64String));
    }
    
    Uint8List dataFromBase64String(String base64String) {
     return base64Decode(base64String);
    }
    
    String base64String(Uint8List data) {
     return base64Encode(data);
    }
    

    使用 'dart:convert' 包有一种更简单的方法

      Image.memory(base64Decode(base64String));
    

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 2013-02-15
      • 2018-09-07
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多