dart - 将图像缓存为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
,我仍然不确定我是否做对了。
任何帮助都会非常感谢。
解决方案
我不建议将二进制文件存储到共享首选项中。特别是因为您正在构建图像缓存。
我只是将它们存储到一个文件中。
Future<File> saveFile(File toBeSaved) async {
final filePath = '${(await getApplicationDocumentsDirectory()).path}/image_cache/image.jpg';
File(filePath)
..createSync(recursive: true)
..writeAsBytes(toBeSaved.readAsBytesSync());
}
这使用getApplicationDocumentsDirectory()
来自路径提供程序包。
推荐阅读
- coldfusion - Testbox 2.1 - 跳过整个目录或 CFC 文件
- reactjs - 基本理解——React 应用中公共目录的位置
- angular - 如何在不需要 rxjs-compat 的情况下只导入 RxJS 6 中使用的运算符,如旧的 RxJS?
- javascript - 如何弄清楚请求是如何在网站中发起的?
- android - 使用 Android Studio 3.1 开发 AOSP 无法为检测测试构建测试 apk
- linux - 如何在 shell 脚本中参数化 git URL?
- angular - ngx数据表根本不呈现
- css - HTML 选项标签中的多种颜色(组合框)
- java - 问题在我的 Java 应用程序上不断重复
- ocaml - 无需使用附加即可取消组合序列的功能