flutter保存图片到相册封装工具类

dart 复制代码
/// 使用 File api
import 'dart:io';

/// 使用 Uint8List 数据类型
import 'dart:typed_data';

/// 图片缓存管理
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/services.dart';

/// 使用 DefaultCacheManager 类(可能无法自动引入,需要手动引入)
import 'package:flutter_cache_manager/flutter_cache_manager.dart';

/// 保存文件或图片到本地
import 'package:image_gallery_saver/image_gallery_saver.dart';

/// 授权管理
import 'package:permission_handler/permission_handler.dart';

class ImageUtil {
  /// 保存图片到相册
  ///
  /// 默认为下载网络图片,如需下载资源图片,需要指定 [isAsset] 为 `true`。
  static Future<bool> 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 =
            image.cacheManager ?? 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 '图片保存失败';
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取阿里云上图片缩略图
  static getOssImageThumbUrl(String url,
      {double width = 350.0, double height, int quality = 80}) {
    if (url.contains('?Size=') || url.contains('?size=')) {
      List<String> strList =
          url.contains('?Size=') ? url.split('?Size=') : url.split('?size=');
      url = strList.first;

      if (height == null) {
        String sizeStr = strList.last;
        List<String> sizeList = sizeStr.split('x');
        double oldImgWid = double.parse(sizeList.first);
        double oldImgHei = double.parse(sizeList.last);
        double newImgWid = width;
        double proportion = oldImgHei / oldImgWid;
        if (proportion > 1) {
          proportion = 4 / 3;
        } else {
          proportion = 3 / 4;
        }
        double newImgHei = proportion * newImgWid;
        url +=
            '?x-oss-process=image/resize,m_fill,w_${newImgWid.floor()},h_${newImgHei.floor()}/quality,q_$quality';
      } else {
        url +=
            '?x-oss-process=image/resize,m_fill,w_${width.floor()},h_${height.floor()}/quality,q_$quality';
      }
    } else {
      if (height != null) {
        url +=
            '?x-oss-process=image/resize,m_fill,w_${width.floor()},h_${height.floor()}/quality,q_$quality';
      }
    }

    return url;
  }
}
相关推荐
problc6 小时前
Flutter中文字体设置指南:打造个性化的应用体验
android·javascript·flutter
lqj_本人14 小时前
鸿蒙next选择 Flutter 开发跨平台应用的原因
flutter·华为·harmonyos
lqj_本人17 小时前
Flutter&鸿蒙next 状态管理框架对比分析
flutter·华为·harmonyos
起司锅仔21 小时前
Flutter启动流程(2)
flutter
hello world smile1 天前
最全的Flutter中pubspec.yaml及其yaml 语法的使用说明
android·前端·javascript·flutter·dart·yaml·pubspec.yaml
lqj_本人1 天前
Flutter 的 Widget 概述与常用 Widgets 与鸿蒙 Next 的对比
flutter·harmonyos
iFlyCai1 天前
极简实现酷炫动效:Flutter隐式动画指南第二篇之一些酷炫的隐式动画效果
flutter
lqj_本人1 天前
Flutter&鸿蒙next 中使用 MobX 进行状态管理
flutter·华为·harmonyos
lqj_本人1 天前
Flutter&鸿蒙next 中的 setState 使用场景与最佳实践
flutter·华为·harmonyos
hello world smile1 天前
Flutter常用命令整理
android·flutter·移动开发·android studio·安卓