image_picker_util.dart 15 KB

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