saveImage static method

Future<void> saveImage(
  1. String imageUrl, {
  2. bool isAsset = false,
})

保存图片到相册 默认为下载网络图片,如需下载资源图片,需要指定 isAssettrue

Implementation

static Future<void> saveImage(String imageUrl, {bool isAsset = false}) async {
  try {
    // if (imageUrl == null) throw '保存失败,图片不存在!';

    /// 权限检测
    // PermissionStatus storageStatus = await Permission.storage.status;
    // if (storageStatus != PermissionStatus.granted) {
    //   storageStatus = await Permission.storage.request();
    //   if (storageStatus != PermissionStatus.granted) {
    //     throw '无法存储图片,请先授权!';
    //   }
    // }

    /// 保存的图片数据
    Uint8List imageBytes;

    if (isAsset == true) {
      /// 保存资源图片
      ByteData bytes = await rootBundle.load(imageUrl);
      imageBytes = bytes.buffer.asUint8List();
    } else {
      /// 保存网络图片
      CachedNetworkImage image = CachedNetworkImage(imageUrl: imageUrl);
      DefaultCacheManager manager = DefaultCacheManager();
      Map<String, String>? headers = image.httpHeaders;
      File file = await manager.getSingleFile(
        image.imageUrl,
        headers: headers,
      );
      imageBytes = await file.readAsBytes();
    }

    /// 保存图片
    final result = await ImageGallerySaver.saveImage(imageBytes);
    if (result == null || result == '') throw '图片保存失败';
    // 提示
    Fluttertoast.showToast(msg: "保存成功");
    debugPrint("保存成功");
  } catch (e) {
    BytedeskUtils.printLog(e.toString());
  }
}