image_picker_util.dart 19 KB

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