image_picker_util.dart 15 KB

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