首页 > 解决方案 > 将图像缓存为base64,然后转换回图像

问题描述

因此,如果上传失败,我会尝试缓存图像,由于当前的抖动限制,我认为我必须将其作为 base64 文件保存到共享首选项,然后从共享首选项中获取它,将其转换回图像然后将其上传到firebase存储。我当前的代码如下所示:

void saveImageToCache(File image) async {
  List<int> imageBytes = image.readAsBytesSync();
  String base64Image = base64Encode(imageBytes); //convert image ready to be cached as a string

  var cachedImageName = "image $fileName";
  instance.setString(cachedImageName, base64Image); // set image name in shared preferences

  var retrievedImage = instance.getString(cachedImageName);// once a connection has been established again, get the image file from the cache and send it to firebase storage as an image
  storageReference.putData(retrievedImage, StorageMetadata(contentType: 'base64'));

  var prefix = "data:image/png;base64,";
  var bStr = retrievedImage.substring(prefix.length);
  var bs = Base64Codec.codec.decodeString(bStr);
  var file = new File("image.png");
  file.writeAsBytesSync(bs.codeUnits);
  uploadTask = storageReference.child(fileName).putFile(file, const StorageMetadata(contentLanguage: "en"));

}

这对我来说是失败的var bStr = retrievedImage.substring(prefix.length);错误type 'String' is not a subtype of type 'Uint8List' where,我仍然不确定我是否做对了。

任何帮助都会非常感谢。

标签: dartflutter

解决方案


我不建议将二进制文件存储到共享首选项中。特别是因为您正在构建图像缓存。

我只是将它们存储到一个文件中。

  Future<File> saveFile(File toBeSaved) async {
    final filePath = '${(await getApplicationDocumentsDirectory()).path}/image_cache/image.jpg';
    File(filePath)
      ..createSync(recursive: true)
      ..writeAsBytes(toBeSaved.readAsBytesSync());
   }

这使用getApplicationDocumentsDirectory()来自路径提供程序包。


推荐阅读