image_picker_util.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import 'dart:io';
  2. import 'dart:math';
  3. import 'package:clean/data/bean/photos_type.dart';
  4. import 'package:clean/model/asset_group.dart';
  5. import 'package:clean/module/locations_photo/locations_photo_controller.dart';
  6. import 'package:clean/module/locations_photo/locations_single_photo_controller.dart';
  7. import 'package:clean/module/people_photo/people_photo_controller.dart';
  8. import 'package:clean/module/people_photo/photo_group.dart';
  9. import 'package:clean/module/photo_preview/photo_preview_controller.dart';
  10. import 'package:clean/module/screenshots_blurry/screenshots_controller.dart';
  11. import 'package:clean/module/similar_photo/similar_photo_controller.dart';
  12. import 'package:flutter/widgets.dart';
  13. import 'package:get/get.dart';
  14. import 'package:photo_manager/photo_manager.dart';
  15. import '../calendar/calendar_state.dart';
  16. class ImagePickerUtil {
  17. ImagePickerUtil._();
  18. static const RequestType permissionType = RequestType.image;
  19. static final RxInt similarPhotoCount = 0.obs;
  20. // 全局存储不同类型的照片
  21. // 截图图片
  22. static final RxList<AssetEntity> screenshotPhotos = <AssetEntity>[].obs;
  23. // 模糊图片
  24. static final RxList<AssetEntity> blurryPhotos = <AssetEntity>[].obs;
  25. // 相似图片
  26. static final RxList<List<AssetEntity>> similarPhotos =
  27. <List<AssetEntity>>[].obs;
  28. // 地点图片
  29. static final RxMap<String, List<AssetEntity>> locationPhotos =
  30. <String, List<AssetEntity>>{}.obs;
  31. // 人物图片
  32. static final RxList<AssetEntity> peoplePhotos = <AssetEntity>[].obs;
  33. // android测试
  34. static late List<AssetEntity> androidPhotos = <AssetEntity>[];
  35. static final RxSet<String> selectedScreenshotPhotosIds = <String>{}.obs;
  36. static final RxSet<String> selectedSimilarPhotosIds = <String>{}.obs;
  37. static final RxSet<String> selectedLocationPhotosIds = <String>{}.obs;
  38. static final RxSet<String> selectedPeoplePhotosIds = <String>{}.obs;
  39. static final RxSet<String> selectedBlurryPhotosIds = <String>{}.obs;
  40. // 添加大小信息的变量
  41. static final Rx<int> screenshotsSize = 0.obs;
  42. static final Rx<int> blurrySize = 0.obs;
  43. static final Rx<int> locationsSize = 0.obs;
  44. static final Rx<int> peopleSize = 0.obs;
  45. static final Rx<int> similarPhotosSize = 0.obs;
  46. // // 用来缓存文件大小
  47. // static final Map<String, double> fileSizeCache = {};
  48. // 清除所有照片数据
  49. static void clearAllPhotos() {
  50. screenshotPhotos.clear();
  51. blurryPhotos.clear();
  52. similarPhotos.clear();
  53. locationPhotos.clear();
  54. peoplePhotos.clear();
  55. }
  56. static Future<void> updatePhotoGroupDate(PhotosType photosType,Set<String> selectedPhotosIds1) async {
  57. // 1. 统一移除相关的照片列表
  58. debugPrint("updatePhotoGroupDate1 ScreenshotsController screenshotController $selectedPhotosIds1");
  59. // 2. 移除控制器中的数据
  60. Set<String> selectedPhotosIds = Set.from(selectedPhotosIds1);
  61. updatePhotoData(selectedPhotosIds);
  62. debugPrint("updatePhotoGroupDate2 ScreenshotsController screenshotController $selectedPhotosIds");
  63. // 3. 根据photosType来处理不同的控制器和photoGroups
  64. switch (photosType) {
  65. case PhotosType.screenshots:
  66. ScreenShotsController screenshotController = Get.find<ScreenShotsController>();
  67. removeImagesAndEmptyGroups(screenshotController, selectedPhotosIds);
  68. selectedScreenshotPhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  69. screenshotController.restoreSelections();
  70. break;
  71. case PhotosType.similarPhotos:
  72. SimilarPhotoController similarController = Get.find<SimilarPhotoController>();
  73. removeImagesAndEmptyGroups(similarController, selectedPhotosIds);
  74. selectedSimilarPhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  75. similarController.restoreSelections();
  76. break;
  77. case PhotosType.locationPhotos:
  78. LocationsSinglePhotoController locationsSingleController = Get.find<LocationsSinglePhotoController>();
  79. LocationsPhotoController locationsPhotoController = Get.find<LocationsPhotoController>();
  80. removeImagesAndEmptyGroups(locationsSingleController, selectedPhotosIds);
  81. removeImagesAndEmptyGroups(locationsPhotoController, selectedPhotosIds);
  82. selectedLocationPhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  83. locationsSingleController.restoreSelections();
  84. locationsPhotoController.restoreSelections();
  85. break;
  86. case PhotosType.peoplePhotos:
  87. PeoplePhotoController peoplePhotoController = Get.find<PeoplePhotoController>();
  88. removeImagesAndEmptyGroups(peoplePhotoController, selectedPhotosIds);
  89. selectedPeoplePhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  90. peoplePhotoController.restoreSelections();
  91. break;
  92. case PhotosType.blurryPhotos:
  93. ScreenShotsController blurryController = Get.find<ScreenShotsController>();
  94. removeImagesAndEmptyGroups(blurryController, selectedPhotosIds);
  95. selectedBlurryPhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  96. blurryController.restoreSelections();
  97. break;
  98. }
  99. }
  100. // 移除每组图片里面对应的元素并删除空的组
  101. static void removeImagesAndEmptyGroups(dynamic controller, Set<String> selectedPhotosIds) {
  102. // 创建photoGroups的副本进行遍历,避免遍历过程中修改photoGroups
  103. for (var group in List.from(controller.photoGroups)) {
  104. // 移除所有与selectedPhotosIds匹配的图片
  105. group.images.removeWhere((image) => selectedPhotosIds.contains(image.id));
  106. // 如果当前组内没有图片了,删除该组
  107. if (group.images.isEmpty) {
  108. controller.photoGroups.remove(group);
  109. }
  110. }
  111. }
  112. static void updatePhotoData(Set<String> selectedPhotosIds1) {
  113. debugPrint("ImagePickerUtil1 updatePhotoData $selectedPhotosIds1");
  114. Set<String> selectedPhotosIds = Set.from(selectedPhotosIds1);
  115. screenshotPhotos.removeWhere((element) => selectedPhotosIds.contains(element.id));
  116. for (var group in similarPhotos) {
  117. group.removeWhere((element) => selectedPhotosIds.contains(element.id));
  118. }
  119. locationPhotos.forEach((key, group) => group.removeWhere((element) => selectedPhotosIds.contains(element.id)));
  120. peoplePhotos.removeWhere((element) => selectedPhotosIds.contains(element.id));
  121. blurryPhotos.removeWhere((element) => selectedPhotosIds.contains(element.id));
  122. // 2. 移除空的集合
  123. similarPhotos.removeWhere((element) => element.isEmpty);
  124. locationPhotos.removeWhere((key, value) => value.isEmpty);
  125. debugPrint("ImagePickerUtil2 updatePhotoData $selectedPhotosIds");
  126. selectedScreenshotPhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  127. selectedSimilarPhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  128. selectedLocationPhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  129. selectedPeoplePhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  130. selectedBlurryPhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  131. debugPrint("ImagePickerUtil3 updatePhotoData $selectedPhotosIds");
  132. CalendarState.removePhotosData(selectedPhotosIds);
  133. }
  134. // 更新照片数据
  135. static Future<void> updatePhotos(
  136. List<Map<String, dynamic>> photoGroups) async {
  137. // clearAllPhotos();
  138. for (var group in photoGroups) {
  139. String type = group['type'] as String;
  140. Map<dynamic, dynamic> groupData = group['group'] as Map<dynamic, dynamic>;
  141. List<dynamic> photos = groupData['photos'] as List<dynamic>;
  142. int totalSize = groupData['totalSize'] as int;
  143. int count = groupData['count'] as int;
  144. switch (type) {
  145. case 'screenshots':
  146. screenshotPhotos.clear();
  147. screenshotPhotos.value = await _convertToAssetEntities(photos);
  148. screenshotsSize.value = totalSize;
  149. break;
  150. case 'similar':
  151. similarPhotos.add(await _convertToAssetEntities(photos));
  152. similarPhotosSize.value = totalSize;
  153. similarPhotoCount.value = count;
  154. break;
  155. case 'location':
  156. String location = group['name'] as String;
  157. locationPhotos[location] = await _convertToAssetEntities(photos);
  158. locationsSize.value = totalSize;
  159. break;
  160. case 'people':
  161. peoplePhotos.clear();
  162. peoplePhotos.value = await _convertToAssetEntities(photos);
  163. peopleSize.value = totalSize;
  164. break;
  165. case 'blurry':
  166. blurryPhotos.clear();
  167. blurryPhotos.value = await _convertToAssetEntities(photos);
  168. blurrySize.value = totalSize;
  169. break;
  170. }
  171. }
  172. }
  173. // 将原始照片数据转换为 AssetEntity 列表
  174. static Future<List<AssetEntity>> _convertToAssetEntities(
  175. List<dynamic> photos) async {
  176. List<AssetEntity> entities = [];
  177. for (var photo in photos) {
  178. final entity = await AssetEntity.fromId(photo['id'] as String);
  179. if (entity != null) {
  180. entities.add(entity);
  181. }
  182. }
  183. return entities;
  184. }
  185. //申请权限
  186. static Future<bool> requestPermissionExtend() async {
  187. final PermissionState ps = await PhotoManager.requestPermissionExtend(
  188. requestOption: const PermissionRequestOption(
  189. androidPermission: AndroidPermission(
  190. type: permissionType,
  191. mediaLocation: false,
  192. )));
  193. return ps.hasAccess;
  194. }
  195. //判断是否有权限
  196. static Future<bool> hasPermission() async {
  197. final PermissionState ps = await PhotoManager.getPermissionState(
  198. requestOption: const PermissionRequestOption(
  199. androidPermission: AndroidPermission(
  200. type: permissionType,
  201. mediaLocation: false,
  202. )));
  203. return ps.hasAccess;
  204. }
  205. static String formatFileSize(int bytes, {int decimals = 2}) {
  206. if (bytes <= 0) return '0 B';
  207. const suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];
  208. var i = (log(bytes) / log(1024)).floor();
  209. // 确保不超过数组范围
  210. i = i < suffixes.length ? i : suffixes.length - 1;
  211. // 计算实际大小
  212. final size = bytes / pow(1024, i);
  213. // 格式化数字,处理小数点位数
  214. String sizeStr;
  215. if (size >= 100) {
  216. // 大于100的只保留整数
  217. sizeStr = size.round().toString();
  218. } else {
  219. // 小于100的保留指定小数位
  220. sizeStr = size.toStringAsFixed(decimals);
  221. }
  222. // 移除末尾的0和不必要的小数点
  223. sizeStr = sizeStr.replaceAll(RegExp(r'\.?0+$'), '');
  224. return '$sizeStr ${suffixes[i]}';
  225. }
  226. /// 直接转换为 GB 单位
  227. static String formatToGB(int bytes, {int decimals = 2}) {
  228. if (bytes <= 0) return '0 GB';
  229. final gb = bytes / pow(1024, 3); // 直接转换为 GB
  230. // 格式化数字,处理小数点位数
  231. String sizeStr;
  232. if (gb >= 100) {
  233. // 大于100的只保留整数
  234. sizeStr = gb.round().toString();
  235. } else {
  236. // 小于100的保留指定小数位
  237. sizeStr = gb.toStringAsFixed(decimals);
  238. }
  239. // 移除末尾的0和不必要的小数点
  240. sizeStr = sizeStr.replaceAll(RegExp(r'\.?0+$'), '');
  241. return '$sizeStr GB';
  242. }
  243. /// 格式化存储大小
  244. static String formatSize(double sizeInGB) {
  245. if (sizeInGB < 0.001) {
  246. // 小于 1MB
  247. return '${(sizeInGB * 1024 * 1024).toStringAsFixed(1)} ';
  248. } else if (sizeInGB < 1) {
  249. // 小于 1GB
  250. return '${(sizeInGB * 1024).toStringAsFixed(1)} ';
  251. } else if (sizeInGB < 1024) {
  252. // 小于 1TB
  253. return '${sizeInGB.toStringAsFixed(1)} ';
  254. } else {
  255. // 大于等于 1TB
  256. return '${(sizeInGB / 1024).toStringAsFixed(1)} ';
  257. }
  258. }
  259. // 加载图片资源
  260. static Future<List<AssetEntity>> loadAssets({bool sortByDate = true}) async {
  261. final PermissionState result = await PhotoManager.requestPermissionExtend();
  262. if (!result.isAuth) return [];
  263. if (androidPhotos.isNotEmpty) return androidPhotos;
  264. // 选择相册
  265. final List<AssetPathEntity> albums = await PhotoManager.getAssetPathList(
  266. type: RequestType.common,
  267. filterOption: FilterOptionGroup(
  268. orders: [
  269. // 根据创建日期排序,降序(最新的在前)
  270. OrderOption(
  271. type: OrderOptionType.createDate,
  272. asc: !sortByDate, // 是否升序排列
  273. ),
  274. ],
  275. ),
  276. );
  277. int assetCount = await albums.first.assetCountAsync;
  278. debugPrint("ImagePickerUtil loadAssets assetCount $assetCount");
  279. androidPhotos = await albums.first.getAssetListPaged(
  280. page: 0,
  281. size: assetCount,
  282. );
  283. return androidPhotos;
  284. }
  285. }