image_picker_util.dart 20 KB

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