image_picker_util.dart 17 KB

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