image_picker_util.dart 17 KB

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