image_picker_util.dart 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. import 'dart:math';
  2. import 'package:clean/data/bean/photos_type.dart';
  3. import 'package:clean/module/locations_photo/locations_photo_state.dart';
  4. import 'package:clean/module/screenshots_blurry/screenshots_blurry_state.dart';
  5. import 'package:clean/module/similar_photo/similar_photo_controller.dart';
  6. import 'package:flutter/widgets.dart';
  7. import 'package:get/get.dart';
  8. import 'package:photo_classifier/models.dart';
  9. import 'package:photo_manager/photo_manager.dart';
  10. import '../../handler/photo_scan_handler.dart';
  11. import '../calendar/calendar_state.dart';
  12. import '../people_photo/people_photo_state.dart';
  13. class ImagePickerUtil {
  14. ImagePickerUtil._();
  15. static const RequestType permissionType = RequestType.image;
  16. static final RxInt similarPhotoCount = 0.obs;
  17. // 全局存储不同类型的照片
  18. // 截图图片
  19. static final RxList<AssetEntity> screenshotPhotos = <AssetEntity>[].obs;
  20. // 模糊图片
  21. static final RxList<AssetEntity> blurryPhotos = <AssetEntity>[].obs;
  22. // 相似图片
  23. static final RxList<List<AssetEntity>> similarPhotos =
  24. <List<AssetEntity>>[].obs;
  25. // 地点图片
  26. static final RxMap<String, List<AssetEntity>> locationPhotos =
  27. <String, List<AssetEntity>>{}.obs;
  28. // 人物图片
  29. static final RxList<AssetEntity> peoplePhotos = <AssetEntity>[].obs;
  30. static late List<AssetEntity> allPhotos = <AssetEntity>[];
  31. static final RxSet<String> selectedScreenshotPhotosIds = <String>{}.obs;
  32. static final RxSet<String> selectedSimilarPhotosIds = <String>{}.obs;
  33. static final RxSet<String> selectedLocationPhotosIds = <String>{}.obs;
  34. static final RxSet<String> selectedPeoplePhotosIds = <String>{}.obs;
  35. static final RxSet<String> selectedBlurryPhotosIds = <String>{}.obs;
  36. // 添加大小信息的变量
  37. static final Rx<int> screenshotsSize = 0.obs;
  38. static final Rx<int> blurrySize = 0.obs;
  39. static final Rx<int> locationsSize = 0.obs;
  40. static final Rx<int> peopleSize = 0.obs;
  41. static final Rx<int> similarPhotosSize = 0.obs;
  42. static var similarResult = <ClassifiedImageGroup>[].obs;
  43. static var allSimilarResult =<ClassifiedImageGroup>[].obs;
  44. static var peopleResult = <ClassifiedImage>[].obs;
  45. static var screenshotResult = <ClassifiedImage>[].obs;
  46. static var blurryResult = <ClassifiedImage>[].obs;
  47. // 清除所有照片数据
  48. static void clearAllPhotos() {
  49. screenshotPhotos.clear();
  50. blurryPhotos.clear();
  51. similarPhotos.clear();
  52. locationPhotos.clear();
  53. peoplePhotos.clear();
  54. }
  55. static loadClassifiedPhotoData(ClassificationResult result) async {
  56. if (result.similarGroups != null) {
  57. similarResult(result.similarGroups ?? []);
  58. await newUpdatePhotoGroups("similar", similarResult);
  59. }
  60. if (result.peopleImages != null) {
  61. peopleResult.addAll(result.peopleImages ?? []);
  62. await newUpdatePhotoGroup("people", peopleResult);
  63. }
  64. if (result.screenshotImages != null) {
  65. screenshotResult.addAll(result.screenshotImages ?? []);
  66. await newUpdatePhotoGroup("screenshots", screenshotResult);
  67. }
  68. if (result.blurryImages != null) {
  69. blurryResult.addAll(result.blurryImages ?? []);
  70. await newUpdatePhotoGroup("blurry", blurryResult);
  71. }
  72. }
  73. static Future<void> updatePhotoGroupDate(
  74. PhotosType photosType, Set<String> selectedPhotosIds1) async {
  75. // // 1. 统一移除相关的照片列表
  76. debugPrint(
  77. "updatePhotoGroupDate1 ScreenshotsController screenshotController $selectedPhotosIds1");
  78. // 2. 移除控制器中的数据
  79. Set<String> selectedPhotosIds = Set.from(selectedPhotosIds1);
  80. updatePhotoData(selectedPhotosIds);
  81. //
  82. debugPrint(
  83. "updatePhotoGroupDate2 ScreenshotsController screenshotController $selectedPhotosIds");
  84. // 3. 根据photosType来处理不同的控制器和photoGroups
  85. switch (photosType) {
  86. case PhotosType.screenshots:
  87. // ScreenShotsController screenshotController = Get.find<ScreenShotsController>();
  88. // removeImagesAndEmptyGroups(screenshotController, selectedPhotosIds);
  89. // selectedScreenshotPhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  90. // screenshotController.restoreSelections();
  91. break;
  92. case PhotosType.similarPhotos:
  93. SimilarPhotoController similarController =
  94. Get.find<SimilarPhotoController>();
  95. removeImagesAndEmptyGroups(similarController, selectedPhotosIds);
  96. selectedSimilarPhotosIds
  97. .removeWhere((element) => selectedPhotosIds.contains(element));
  98. similarController.restoreSelections();
  99. break;
  100. case PhotosType.locationPhotos:
  101. // LocationsSinglePhotoController locationsSingleController = Get.find<LocationsSinglePhotoController>();
  102. // LocationsPhotoController locationsPhotoController = Get.find<LocationsPhotoController>();
  103. // removeImagesAndEmptyGroups(locationsSingleController, selectedPhotosIds);
  104. // removeImagesAndEmptyGroups(locationsPhotoController, selectedPhotosIds);
  105. // selectedLocationPhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  106. // locationsSingleController.restoreSelections();
  107. // locationsPhotoController.restoreSelections();
  108. break;
  109. case PhotosType.peoplePhotos:
  110. // PeoplePhotoController peoplePhotoController = Get.find<PeoplePhotoController>();
  111. // removeImagesAndEmptyGroups(peoplePhotoController, selectedPhotosIds);
  112. // selectedPeoplePhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  113. // peoplePhotoController.restoreSelections();
  114. break;
  115. case PhotosType.blurryPhotos:
  116. // ScreenShotsController blurryController = Get.find<ScreenShotsController>();
  117. // removeImagesAndEmptyGroups(blurryController, selectedPhotosIds);
  118. // selectedBlurryPhotosIds.removeWhere((element) => selectedPhotosIds.contains(element));
  119. // blurryController.restoreSelections();
  120. break;
  121. }
  122. }
  123. // 移除每组图片里面对应的元素并删除空的组
  124. static void removeImagesAndEmptyGroups(
  125. dynamic controller, Set<String> selectedPhotosIds) {
  126. // 创建photoGroups的副本进行遍历,避免遍历过程中修改photoGroups
  127. for (var group in List.from(controller.photoGroups)) {
  128. // 移除所有与selectedPhotosIds匹配的图片
  129. group.images.removeWhere((image) => selectedPhotosIds.contains(image.id));
  130. // 如果当前组内没有图片了,删除该组
  131. if (group.images.isEmpty) {
  132. controller.photoGroups.remove(group);
  133. }
  134. }
  135. }
  136. static void updatePhotoData(Set<String> selectedPhotosIds1) {
  137. debugPrint("ImagePickerUtil1 updatePhotoData $selectedPhotosIds1");
  138. Set<String> selectedPhotosIds = Set.from(selectedPhotosIds1);
  139. screenshotPhotos
  140. .removeWhere((element) => selectedPhotosIds.contains(element.id));
  141. blurryPhotos
  142. .removeWhere((element) => selectedPhotosIds.contains(element.id));
  143. ScreenshotsBlurryState.removePhotosData(selectedPhotosIds);
  144. for (var group in similarPhotos) {
  145. group.removeWhere((element) => selectedPhotosIds.contains(element.id));
  146. }
  147. locationPhotos.forEach((key, group) =>
  148. group.removeWhere((element) => selectedPhotosIds.contains(element.id)));
  149. LocationsPhotoState.removePhotosData(selectedPhotosIds);
  150. peoplePhotos
  151. .removeWhere((element) => selectedPhotosIds.contains(element.id));
  152. PeoplePhotoState.removePhotosData(selectedPhotosIds);
  153. similarPhotos.removeWhere((element) => element.isEmpty);
  154. locationPhotos.removeWhere((key, value) => value.isEmpty);
  155. debugPrint("ImagePickerUtil updatePhotoData $selectedPhotosIds");
  156. selectedScreenshotPhotosIds
  157. .removeWhere((element) => selectedPhotosIds.contains(element));
  158. selectedSimilarPhotosIds
  159. .removeWhere((element) => selectedPhotosIds.contains(element));
  160. selectedLocationPhotosIds
  161. .removeWhere((element) => selectedPhotosIds.contains(element));
  162. selectedPeoplePhotosIds
  163. .removeWhere((element) => selectedPhotosIds.contains(element));
  164. selectedBlurryPhotosIds
  165. .removeWhere((element) => selectedPhotosIds.contains(element));
  166. if (PhotoScanHandler.locationPhoto.value != null &&
  167. selectedPhotosIds.contains(PhotoScanHandler.locationPhoto.value!.id)) {
  168. PhotoScanHandler.locationPhoto.value = null;
  169. if (locationPhotos.isNotEmpty) {
  170. var asset = locationPhotos.values.first.first;
  171. PhotoScanHandler.locationPhoto.value = asset;
  172. }
  173. }
  174. if (PhotoScanHandler.screenshotPhoto.value != null &&
  175. selectedPhotosIds
  176. .contains(PhotoScanHandler.screenshotPhoto.value!.id)) {
  177. PhotoScanHandler.screenshotPhoto.value = null;
  178. if (screenshotPhotos.isNotEmpty) {
  179. var asset = screenshotPhotos.first;
  180. PhotoScanHandler.screenshotPhoto.value = asset;
  181. }
  182. }
  183. if (PhotoScanHandler.blurryPhoto.value != null &&
  184. selectedPhotosIds.contains(PhotoScanHandler.blurryPhoto.value!.id)) {
  185. PhotoScanHandler.blurryPhoto.value = null;
  186. if (blurryPhotos.isNotEmpty) {
  187. var asset = blurryPhotos.first;
  188. PhotoScanHandler.blurryPhoto.value = asset;
  189. }
  190. }
  191. PhotoScanHandler.similarPhotos
  192. .removeWhere((element) => selectedPhotosIds.contains(element.id));
  193. if (PhotoScanHandler.locationPhoto.value != null &&
  194. selectedPhotosIds.contains(PhotoScanHandler.locationPhoto.value!.id)) {
  195. PhotoScanHandler.locationPhoto.value = null;
  196. }
  197. if (similarPhotos.isNotEmpty) {
  198. for (var group in ImagePickerUtil.similarPhotos) {
  199. for (var asset in group) {
  200. PhotoScanHandler.similarPhotos.add(asset);
  201. if (PhotoScanHandler.similarPhotos.length == 4) {
  202. break;
  203. }
  204. }
  205. }
  206. }
  207. PhotoScanHandler.peoplePhotos
  208. .removeWhere((element) => selectedPhotosIds.contains(element.id));
  209. if (peoplePhotos.isNotEmpty) {
  210. for (var personPhotos in peoplePhotos) {
  211. PhotoScanHandler.peoplePhotos.add(personPhotos);
  212. if (PhotoScanHandler.peoplePhotos.length == 2) {
  213. break;
  214. }
  215. }
  216. }
  217. peopleResult
  218. .removeWhere((element) => selectedPhotosIds.contains(element.assetsId));
  219. peopleSize.value =
  220. peopleResult.fold(0, (sum, image) => sum + image.fileSize);
  221. screenshotResult
  222. .removeWhere((element) => selectedPhotosIds.contains(element.assetsId));
  223. screenshotsSize.value =
  224. screenshotResult.fold(0, (sum, image) => sum + image.fileSize);
  225. blurryResult
  226. .removeWhere((element) => selectedPhotosIds.contains(element.assetsId));
  227. blurrySize.value =
  228. blurryResult.fold(0, (sum, image) => sum + image.fileSize);
  229. similarPhotosSize.value=0;
  230. similarPhotoCount.value=0;
  231. for (var group in allSimilarResult) {
  232. group.images.removeWhere(
  233. (element) => selectedPhotosIds.contains(element.assetsId));
  234. similarPhotosSize.value += group.images.fold(0, (sum, image) => sum + image.fileSize);
  235. similarPhotoCount.value += group.images.length;
  236. }
  237. debugPrint("ImagePickerUtil3 updatePhotoData $selectedPhotosIds");
  238. CalendarState.removePhotosData(selectedPhotosIds);
  239. }
  240. // 更新照片数据
  241. static Future<void> updatePhotos(
  242. List<Map<String, dynamic>> photoGroups) async {
  243. // clearAllPhotos();
  244. for (var group in photoGroups) {
  245. String type = group['type'] as String;
  246. Map<dynamic, dynamic> groupData = group['group'] as Map<dynamic, dynamic>;
  247. List<dynamic> photos = groupData['photos'] as List<dynamic>;
  248. int totalSize = groupData['totalSize'] as int;
  249. int count = groupData['count'] as int;
  250. switch (type) {
  251. case 'screenshots':
  252. screenshotPhotos.clear();
  253. screenshotPhotos.value = await _convertToAssetEntities(photos);
  254. screenshotsSize.value = totalSize;
  255. break;
  256. case 'similar':
  257. similarPhotos.add(await _convertToAssetEntities(photos));
  258. similarPhotosSize.value = totalSize;
  259. similarPhotoCount.value = count;
  260. break;
  261. case 'location':
  262. String location = group['name'] as String;
  263. locationPhotos[location] = await _convertToAssetEntities(photos);
  264. locationsSize.value = totalSize;
  265. break;
  266. case 'people':
  267. peoplePhotos.clear();
  268. peoplePhotos.value = await _convertToAssetEntities(photos);
  269. peopleSize.value = totalSize;
  270. break;
  271. case 'blurry':
  272. blurryPhotos.clear();
  273. blurryPhotos.value = await _convertToAssetEntities(photos);
  274. blurrySize.value = totalSize;
  275. break;
  276. }
  277. }
  278. }
  279. static Future<void> newUpdatePhotoGroups(
  280. String type, List<ClassifiedImageGroup> photoGroup) async {
  281. if (type == 'similar') {
  282. // similarPhotos.clear();
  283. for (var group in photoGroup) {
  284. similarPhotos.add(await _newConvertToAssetEntities(group.images));
  285. similarPhotosSize.value += group.groupFileSize;
  286. similarPhotoCount.value += group.groupImageCount;
  287. allSimilarResult.add(group);
  288. }
  289. for (final group in ImagePickerUtil.similarPhotos) {
  290. for (final asset in group) {
  291. if (PhotoScanHandler.similarPhotos.length >= 4) break;
  292. if(PhotoScanHandler.similarPhotos.contains(asset)) continue;
  293. PhotoScanHandler.similarPhotos.add(asset);
  294. }
  295. if (PhotoScanHandler.similarPhotos.length >= 4) break;
  296. }
  297. }
  298. }
  299. static Future<void> newUpdatePhotoGroup(
  300. String type, List<ClassifiedImage> photoGroup) async {
  301. switch (type) {
  302. case 'screenshots':
  303. screenshotPhotos.clear();
  304. screenshotPhotos.value = await _newConvertToAssetEntities(photoGroup);
  305. screenshotsSize.value =
  306. photoGroup.fold(0, (sum, image) => sum + image.fileSize);
  307. if (ImagePickerUtil.screenshotPhotos.isNotEmpty) {
  308. PhotoScanHandler.screenshotPhoto.value = ImagePickerUtil.screenshotPhotos.first;
  309. }
  310. break;
  311. // case 'location':
  312. // String location = group['name'] as String;
  313. // locationPhotos[location] = await _convertToAssetEntities(photos);
  314. // locationsSize.value = totalSize;
  315. break;
  316. case 'people':
  317. peoplePhotos.clear();
  318. peoplePhotos.assignAll(await _newConvertToAssetEntities(photoGroup));
  319. peopleSize.value =
  320. photoGroup.fold(0, (sum, image) => sum + image.fileSize);
  321. for (final person in ImagePickerUtil.peoplePhotos) {
  322. if (PhotoScanHandler.peoplePhotos.length >= 2) break;
  323. if(PhotoScanHandler.peoplePhotos.contains(person)) continue;
  324. PhotoScanHandler.peoplePhotos.add(person);
  325. }
  326. break;
  327. case 'blurry':
  328. blurryPhotos.clear();
  329. blurryPhotos.value = await _newConvertToAssetEntities(photoGroup);
  330. blurrySize.value =
  331. photoGroup.fold(0, (sum, image) => sum + image.fileSize);
  332. if (ImagePickerUtil.blurryPhotos.isNotEmpty) {
  333. PhotoScanHandler.blurryPhoto.value = ImagePickerUtil.blurryPhotos.first;
  334. }
  335. break;
  336. }
  337. }
  338. // 将原始照片数据转换为 AssetEntity 列表
  339. static Future<List<AssetEntity>> _convertToAssetEntities(
  340. List<dynamic> photos) async {
  341. List<AssetEntity> entities = [];
  342. for (var photo in photos) {
  343. final entity = await AssetEntity.fromId(photo['id'] as String);
  344. if (entity != null) {
  345. entities.add(entity);
  346. }
  347. }
  348. return entities;
  349. }
  350. // 新版将原始照片数据转换为AssetsEntity列表
  351. static Future<List<AssetEntity>> _newConvertToAssetEntities(
  352. List<ClassifiedImage> photos) async {
  353. List<AssetEntity> entities = [];
  354. for (var photo in photos) {
  355. final entity = await AssetEntity.fromId(photo.assetsId);
  356. if (entity != null) {
  357. entities.add(entity);
  358. }
  359. }
  360. return entities;
  361. }
  362. //申请权限
  363. static Future<bool> requestPermissionExtend() async {
  364. final PermissionState ps = await PhotoManager.requestPermissionExtend(
  365. requestOption: const PermissionRequestOption(
  366. androidPermission: AndroidPermission(
  367. type: permissionType,
  368. mediaLocation: false,
  369. )));
  370. return ps.hasAccess;
  371. }
  372. //判断是否有权限
  373. static Future<bool> hasPermission() async {
  374. final PermissionState ps = await PhotoManager.getPermissionState(
  375. requestOption: const PermissionRequestOption(
  376. androidPermission: AndroidPermission(
  377. type: permissionType,
  378. mediaLocation: false,
  379. )));
  380. return ps.hasAccess;
  381. }
  382. static String formatFileSize(int bytes, {int decimals = 2}) {
  383. if (bytes <= 0) return '0 B';
  384. const suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];
  385. var i = (log(bytes) / log(1024)).floor();
  386. // 确保不超过数组范围
  387. i = i < suffixes.length ? i : suffixes.length - 1;
  388. // 计算实际大小
  389. final size = bytes / pow(1024, i);
  390. // 格式化数字,处理小数点位数
  391. String sizeStr;
  392. if (size >= 100) {
  393. // 大于100的只保留整数
  394. sizeStr = size.round().toString();
  395. } else {
  396. // 小于100的保留指定小数位
  397. sizeStr = size.toStringAsFixed(decimals);
  398. }
  399. // 移除末尾的0和不必要的小数点
  400. sizeStr = sizeStr.replaceAll(RegExp(r'\.?0+$'), '');
  401. return '$sizeStr ${suffixes[i]}';
  402. }
  403. /// 直接转换为 GB 单位
  404. static String formatToGB(int bytes, {int decimals = 2}) {
  405. if (bytes <= 0) return '0 GB';
  406. final gb = bytes / pow(1024, 3); // 直接转换为 GB
  407. // 格式化数字,处理小数点位数
  408. String sizeStr;
  409. if (gb >= 100) {
  410. // 大于100的只保留整数
  411. sizeStr = gb.round().toString();
  412. } else {
  413. // 小于100的保留指定小数位
  414. sizeStr = gb.toStringAsFixed(decimals);
  415. }
  416. // 移除末尾的0和不必要的小数点
  417. sizeStr = sizeStr.replaceAll(RegExp(r'\.?0+$'), '');
  418. return '$sizeStr GB';
  419. }
  420. /// 格式化存储大小
  421. static String formatSize(double sizeInGB) {
  422. if (sizeInGB < 0.001) {
  423. // 小于 1MB
  424. return '${(sizeInGB * 1024 * 1024).toStringAsFixed(1)} ';
  425. } else if (sizeInGB < 1) {
  426. // 小于 1GB
  427. return '${(sizeInGB * 1024).toStringAsFixed(1)} ';
  428. } else if (sizeInGB < 1024) {
  429. // 小于 1TB
  430. return '${sizeInGB.toStringAsFixed(1)} ';
  431. } else {
  432. // 大于等于 1TB
  433. return '${(sizeInGB / 1024).toStringAsFixed(1)} ';
  434. }
  435. }
  436. static Future<List<AssetEntity>> loadAssetsPaged({
  437. int page = 0,
  438. int pageSize = 9,
  439. bool sortByDate = true,
  440. }) async {
  441. final PermissionState result = await PhotoManager.requestPermissionExtend();
  442. if (!result.hasAccess) return [];
  443. // 获取相册列表(这里只取第一个相册)
  444. final List<AssetPathEntity> albums = await PhotoManager.getAssetPathList(
  445. type: RequestType.common,
  446. filterOption: FilterOptionGroup(
  447. orders: [
  448. OrderOption(
  449. type: OrderOptionType.createDate,
  450. asc: !sortByDate,
  451. ),
  452. ],
  453. ),
  454. );
  455. if (albums.isEmpty) return [];
  456. final AssetPathEntity album = albums.first;
  457. // 分页加载当前页的照片
  458. final List<AssetEntity> assets = await album.getAssetListPaged(
  459. page: page,
  460. size: pageSize,
  461. );
  462. return assets;
  463. }
  464. // 加载图片资源
  465. static Future<List<AssetEntity>> loadAssets({bool sortByDate = true}) async {
  466. final PermissionState result = await PhotoManager.requestPermissionExtend();
  467. if (!result.hasAccess) return [];
  468. if (allPhotos.isNotEmpty) return allPhotos;
  469. // 选择相册
  470. final List<AssetPathEntity> albums = await PhotoManager.getAssetPathList(
  471. type: RequestType.common,
  472. filterOption: FilterOptionGroup(
  473. orders: [
  474. // 根据创建日期排序,降序(最新的在前)
  475. OrderOption(
  476. type: OrderOptionType.createDate,
  477. asc: !sortByDate, // 是否升序排列
  478. ),
  479. ],
  480. ),
  481. );
  482. int assetCount = await albums.first.assetCountAsync;
  483. debugPrint("ImagePickerUtil loadAssets assetCount $assetCount");
  484. allPhotos = await albums.first.getAssetListPaged(
  485. page: 0,
  486. size: assetCount,
  487. );
  488. return allPhotos;
  489. }
  490. }