image_picker_util.dart 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. debugPrint("ImagePickerUtil3 updatePhotoData $selectedPhotosIds");
  239. CalendarState.removePhotosData(selectedPhotosIds);
  240. }
  241. // 更新照片数据
  242. static Future<void> updatePhotos(
  243. List<Map<String, dynamic>> photoGroups) async {
  244. // clearAllPhotos();
  245. for (var group in photoGroups) {
  246. String type = group['type'] as String;
  247. Map<dynamic, dynamic> groupData = group['group'] as Map<dynamic, dynamic>;
  248. List<dynamic> photos = groupData['photos'] as List<dynamic>;
  249. int totalSize = groupData['totalSize'] as int;
  250. int count = groupData['count'] as int;
  251. switch (type) {
  252. case 'screenshots':
  253. screenshotPhotos.clear();
  254. screenshotPhotos.value = await _convertToAssetEntities(photos);
  255. screenshotsSize.value = totalSize;
  256. break;
  257. case 'similar':
  258. similarPhotos.add(await _convertToAssetEntities(photos));
  259. similarPhotosSize.value = totalSize;
  260. similarPhotoCount.value = count;
  261. break;
  262. case 'location':
  263. String location = group['name'] as String;
  264. locationPhotos[location] = await _convertToAssetEntities(photos);
  265. locationsSize.value = totalSize;
  266. break;
  267. case 'people':
  268. peoplePhotos.clear();
  269. peoplePhotos.value = await _convertToAssetEntities(photos);
  270. peopleSize.value = totalSize;
  271. break;
  272. case 'blurry':
  273. blurryPhotos.clear();
  274. blurryPhotos.value = await _convertToAssetEntities(photos);
  275. blurrySize.value = totalSize;
  276. break;
  277. }
  278. }
  279. }
  280. static Future<void> newUpdatePhotoGroups(
  281. String type, List<ClassifiedImageGroup> photoGroup) async {
  282. if (type == 'similar') {
  283. // similarPhotos.clear();
  284. for (var group in photoGroup) {
  285. similarPhotos.add(await _newConvertToAssetEntities(group.images));
  286. similarPhotosSize.value += group.groupFileSize;
  287. similarPhotoCount.value += group.groupImageCount;
  288. }
  289. }
  290. }
  291. static Future<void> newUpdatePhotoGroup(
  292. String type, List<ClassifiedImage> photoGroup) async {
  293. switch (type) {
  294. case 'screenshots':
  295. screenshotPhotos.clear();
  296. screenshotPhotos.value = await _newConvertToAssetEntities(photoGroup);
  297. screenshotsSize.value =
  298. photoGroup.fold(0, (sum, image) => sum + image.fileSize);
  299. break;
  300. // case 'location':
  301. // String location = group['name'] as String;
  302. // locationPhotos[location] = await _convertToAssetEntities(photos);
  303. // locationsSize.value = totalSize;
  304. break;
  305. case 'people':
  306. peoplePhotos.clear();
  307. peoplePhotos.assignAll(await _newConvertToAssetEntities(photoGroup));
  308. peopleSize.value =
  309. photoGroup.fold(0, (sum, image) => sum + image.fileSize);
  310. break;
  311. case 'blurry':
  312. blurryPhotos.clear();
  313. blurryPhotos.value = await _newConvertToAssetEntities(photoGroup);
  314. blurrySize.value =
  315. photoGroup.fold(0, (sum, image) => sum + image.fileSize);
  316. break;
  317. }
  318. }
  319. // 将原始照片数据转换为 AssetEntity 列表
  320. static Future<List<AssetEntity>> _convertToAssetEntities(
  321. List<dynamic> photos) async {
  322. List<AssetEntity> entities = [];
  323. for (var photo in photos) {
  324. final entity = await AssetEntity.fromId(photo['id'] as String);
  325. if (entity != null) {
  326. entities.add(entity);
  327. }
  328. }
  329. return entities;
  330. }
  331. // 新版将原始照片数据转换为AssetsEntity列表
  332. static Future<List<AssetEntity>> _newConvertToAssetEntities(
  333. List<ClassifiedImage> photos) async {
  334. List<AssetEntity> entities = [];
  335. for (var photo in photos) {
  336. final entity = await AssetEntity.fromId(photo.assetsId);
  337. if (entity != null) {
  338. entities.add(entity);
  339. }
  340. }
  341. return entities;
  342. }
  343. //申请权限
  344. static Future<bool> requestPermissionExtend() async {
  345. final PermissionState ps = await PhotoManager.requestPermissionExtend(
  346. requestOption: const PermissionRequestOption(
  347. androidPermission: AndroidPermission(
  348. type: permissionType,
  349. mediaLocation: false,
  350. )));
  351. return ps.hasAccess;
  352. }
  353. //判断是否有权限
  354. static Future<bool> hasPermission() async {
  355. final PermissionState ps = await PhotoManager.getPermissionState(
  356. requestOption: const PermissionRequestOption(
  357. androidPermission: AndroidPermission(
  358. type: permissionType,
  359. mediaLocation: false,
  360. )));
  361. return ps.hasAccess;
  362. }
  363. static String formatFileSize(int bytes, {int decimals = 2}) {
  364. if (bytes <= 0) return '0 B';
  365. const suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];
  366. var i = (log(bytes) / log(1024)).floor();
  367. // 确保不超过数组范围
  368. i = i < suffixes.length ? i : suffixes.length - 1;
  369. // 计算实际大小
  370. final size = bytes / pow(1024, i);
  371. // 格式化数字,处理小数点位数
  372. String sizeStr;
  373. if (size >= 100) {
  374. // 大于100的只保留整数
  375. sizeStr = size.round().toString();
  376. } else {
  377. // 小于100的保留指定小数位
  378. sizeStr = size.toStringAsFixed(decimals);
  379. }
  380. // 移除末尾的0和不必要的小数点
  381. sizeStr = sizeStr.replaceAll(RegExp(r'\.?0+$'), '');
  382. return '$sizeStr ${suffixes[i]}';
  383. }
  384. /// 直接转换为 GB 单位
  385. static String formatToGB(int bytes, {int decimals = 2}) {
  386. if (bytes <= 0) return '0 GB';
  387. final gb = bytes / pow(1024, 3); // 直接转换为 GB
  388. // 格式化数字,处理小数点位数
  389. String sizeStr;
  390. if (gb >= 100) {
  391. // 大于100的只保留整数
  392. sizeStr = gb.round().toString();
  393. } else {
  394. // 小于100的保留指定小数位
  395. sizeStr = gb.toStringAsFixed(decimals);
  396. }
  397. // 移除末尾的0和不必要的小数点
  398. sizeStr = sizeStr.replaceAll(RegExp(r'\.?0+$'), '');
  399. return '$sizeStr GB';
  400. }
  401. /// 格式化存储大小
  402. static String formatSize(double sizeInGB) {
  403. if (sizeInGB < 0.001) {
  404. // 小于 1MB
  405. return '${(sizeInGB * 1024 * 1024).toStringAsFixed(1)} ';
  406. } else if (sizeInGB < 1) {
  407. // 小于 1GB
  408. return '${(sizeInGB * 1024).toStringAsFixed(1)} ';
  409. } else if (sizeInGB < 1024) {
  410. // 小于 1TB
  411. return '${sizeInGB.toStringAsFixed(1)} ';
  412. } else {
  413. // 大于等于 1TB
  414. return '${(sizeInGB / 1024).toStringAsFixed(1)} ';
  415. }
  416. }
  417. static Future<List<AssetEntity>> loadAssetsPaged({
  418. int page = 0,
  419. int pageSize = 9,
  420. bool sortByDate = true,
  421. }) async {
  422. final PermissionState result = await PhotoManager.requestPermissionExtend();
  423. if (!result.hasAccess) return [];
  424. // 获取相册列表(这里只取第一个相册)
  425. final List<AssetPathEntity> albums = await PhotoManager.getAssetPathList(
  426. type: RequestType.common,
  427. filterOption: FilterOptionGroup(
  428. orders: [
  429. OrderOption(
  430. type: OrderOptionType.createDate,
  431. asc: !sortByDate,
  432. ),
  433. ],
  434. ),
  435. );
  436. if (albums.isEmpty) return [];
  437. final AssetPathEntity album = albums.first;
  438. // 分页加载当前页的照片
  439. final List<AssetEntity> assets = await album.getAssetListPaged(
  440. page: page,
  441. size: pageSize,
  442. );
  443. return assets;
  444. }
  445. // 加载图片资源
  446. static Future<List<AssetEntity>> loadAssets({bool sortByDate = true}) async {
  447. final PermissionState result = await PhotoManager.requestPermissionExtend();
  448. if (!result.hasAccess) return [];
  449. if (androidPhotos.isNotEmpty) return androidPhotos;
  450. // 选择相册
  451. final List<AssetPathEntity> albums = await PhotoManager.getAssetPathList(
  452. type: RequestType.common,
  453. filterOption: FilterOptionGroup(
  454. orders: [
  455. // 根据创建日期排序,降序(最新的在前)
  456. OrderOption(
  457. type: OrderOptionType.createDate,
  458. asc: !sortByDate, // 是否升序排列
  459. ),
  460. ],
  461. ),
  462. );
  463. int assetCount = await albums.first.assetCountAsync;
  464. debugPrint("ImagePickerUtil loadAssets assetCount $assetCount");
  465. androidPhotos = await albums.first.getAssetListPaged(
  466. page: 0,
  467. size: assetCount,
  468. );
  469. return androidPhotos;
  470. }
  471. }