image_picker_util.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import 'dart:io';
  2. import 'dart:math';
  3. import 'package:clean/data/bean/photos_type.dart';
  4. import 'package:clean/model/asset_group.dart';
  5. import 'package:clean/module/locations_photo/locations_photo_controller.dart';
  6. import 'package:clean/module/locations_photo/locations_single_photo_controller.dart';
  7. import 'package:clean/module/people_photo/people_photo_controller.dart';
  8. import 'package:clean/module/people_photo/photo_group.dart';
  9. import 'package:clean/module/photo_preview/photo_preview_controller.dart';
  10. import 'package:clean/module/screenshots_blurry/screenshots_controller.dart';
  11. import 'package:clean/module/similar_photo/similar_photo_controller.dart';
  12. import 'package:flutter/widgets.dart';
  13. import 'package:get/get.dart';
  14. import 'package:photo_manager/photo_manager.dart';
  15. import '../calendar/calendar_state.dart';
  16. import '../home/home_controller.dart';
  17. class ImagePickerUtil {
  18. ImagePickerUtil._();
  19. static const RequestType permissionType = RequestType.image;
  20. static final RxInt similarPhotoCount = 0.obs;
  21. // 全局存储不同类型的照片
  22. // 截图图片
  23. static final RxList<AssetEntity> screenshotPhotos = <AssetEntity>[].obs;
  24. // 模糊图片
  25. static final RxList<AssetEntity> blurryPhotos = <AssetEntity>[].obs;
  26. // 相似图片
  27. static final RxList<List<AssetEntity>> similarPhotos =
  28. <List<AssetEntity>>[].obs;
  29. // 地点图片
  30. static final RxMap<String, List<AssetEntity>> locationPhotos =
  31. <String, List<AssetEntity>>{}.obs;
  32. // 人物图片
  33. static final RxList<AssetEntity> peoplePhotos = <AssetEntity>[].obs;
  34. // android测试
  35. static late List<AssetEntity> androidPhotos = <AssetEntity>[];
  36. static final RxSet<String> selectedScreenshotPhotosIds = <String>{}.obs;
  37. static final RxSet<String> selectedSimilarPhotosIds = <String>{}.obs;
  38. static final RxSet<String> selectedLocationPhotosIds = <String>{}.obs;
  39. static final RxSet<String> selectedPeoplePhotosIds = <String>{}.obs;
  40. static final RxSet<String> selectedBlurryPhotosIds = <String>{}.obs;
  41. // 添加大小信息的变量
  42. static final Rx<int> screenshotsSize = 0.obs;
  43. static final Rx<int> blurrySize = 0.obs;
  44. static final Rx<int> locationsSize = 0.obs;
  45. static final Rx<int> peopleSize = 0.obs;
  46. static final Rx<int> similarPhotosSize = 0.obs;
  47. // // 用来缓存文件大小
  48. // static final Map<String, double> fileSizeCache = {};
  49. // 清除所有照片数据
  50. static void clearAllPhotos() {
  51. screenshotPhotos.clear();
  52. blurryPhotos.clear();
  53. similarPhotos.clear();
  54. locationPhotos.clear();
  55. peoplePhotos.clear();
  56. }
  57. static Future<void> updatePhotoGroupDate(
  58. PhotosType photosType, Set<String> selectedPhotosIds1) async {
  59. // 1. 统一移除相关的照片列表
  60. debugPrint(
  61. "updatePhotoGroupDate1 ScreenshotsController screenshotController $selectedPhotosIds1");
  62. // 2. 移除控制器中的数据
  63. Set<String> selectedPhotosIds = Set.from(selectedPhotosIds1);
  64. updatePhotoData(selectedPhotosIds);
  65. debugPrint(
  66. "updatePhotoGroupDate2 ScreenshotsController screenshotController $selectedPhotosIds");
  67. // 3. 根据photosType来处理不同的控制器和photoGroups
  68. switch (photosType) {
  69. case PhotosType.screenshots:
  70. ScreenShotsController screenshotController =
  71. Get.find<ScreenShotsController>();
  72. removeImagesAndEmptyGroups(screenshotController, selectedPhotosIds);
  73. selectedScreenshotPhotosIds
  74. .removeWhere((element) => selectedPhotosIds.contains(element));
  75. screenshotController.restoreSelections();
  76. break;
  77. case PhotosType.similarPhotos:
  78. SimilarPhotoController similarController =
  79. Get.find<SimilarPhotoController>();
  80. removeImagesAndEmptyGroups(similarController, selectedPhotosIds);
  81. selectedSimilarPhotosIds
  82. .removeWhere((element) => selectedPhotosIds.contains(element));
  83. similarController.restoreSelections();
  84. break;
  85. case PhotosType.locationPhotos:
  86. LocationsSinglePhotoController locationsSingleController =
  87. Get.find<LocationsSinglePhotoController>();
  88. LocationsPhotoController locationsPhotoController =
  89. Get.find<LocationsPhotoController>();
  90. removeImagesAndEmptyGroups(
  91. locationsSingleController, selectedPhotosIds);
  92. removeImagesAndEmptyGroups(locationsPhotoController, selectedPhotosIds);
  93. selectedLocationPhotosIds
  94. .removeWhere((element) => selectedPhotosIds.contains(element));
  95. locationsSingleController.restoreSelections();
  96. locationsPhotoController.restoreSelections();
  97. break;
  98. case PhotosType.peoplePhotos:
  99. PeoplePhotoController peoplePhotoController =
  100. Get.find<PeoplePhotoController>();
  101. removeImagesAndEmptyGroups(peoplePhotoController, selectedPhotosIds);
  102. selectedPeoplePhotosIds
  103. .removeWhere((element) => selectedPhotosIds.contains(element));
  104. peoplePhotoController.restoreSelections();
  105. break;
  106. case PhotosType.blurryPhotos:
  107. ScreenShotsController blurryController =
  108. Get.find<ScreenShotsController>();
  109. removeImagesAndEmptyGroups(blurryController, selectedPhotosIds);
  110. selectedBlurryPhotosIds
  111. .removeWhere((element) => selectedPhotosIds.contains(element));
  112. blurryController.restoreSelections();
  113. break;
  114. }
  115. }
  116. // 移除每组图片里面对应的元素并删除空的组
  117. static void removeImagesAndEmptyGroups(
  118. dynamic controller, Set<String> selectedPhotosIds) {
  119. // 创建photoGroups的副本进行遍历,避免遍历过程中修改photoGroups
  120. for (var group in List.from(controller.photoGroups)) {
  121. // 移除所有与selectedPhotosIds匹配的图片
  122. group.images.removeWhere((image) => selectedPhotosIds.contains(image.id));
  123. // 如果当前组内没有图片了,删除该组
  124. if (group.images.isEmpty) {
  125. controller.photoGroups.remove(group);
  126. }
  127. }
  128. }
  129. static void updatePhotoData(Set<String> selectedPhotosIds1) {
  130. debugPrint("ImagePickerUtil1 updatePhotoData $selectedPhotosIds1");
  131. Set<String> selectedPhotosIds = Set.from(selectedPhotosIds1);
  132. screenshotPhotos
  133. .removeWhere((element) => selectedPhotosIds.contains(element.id));
  134. for (var group in similarPhotos) {
  135. group.removeWhere((element) => selectedPhotosIds.contains(element.id));
  136. }
  137. locationPhotos.forEach((key, group) =>
  138. group.removeWhere((element) => selectedPhotosIds.contains(element.id)));
  139. peoplePhotos
  140. .removeWhere((element) => selectedPhotosIds.contains(element.id));
  141. blurryPhotos
  142. .removeWhere((element) => selectedPhotosIds.contains(element.id));
  143. // 2. 移除空的集合
  144. similarPhotos.removeWhere((element) => element.isEmpty);
  145. locationPhotos.removeWhere((key, value) => value.isEmpty);
  146. debugPrint("ImagePickerUtil2 updatePhotoData $selectedPhotosIds");
  147. selectedScreenshotPhotosIds
  148. .removeWhere((element) => selectedPhotosIds.contains(element));
  149. selectedSimilarPhotosIds
  150. .removeWhere((element) => selectedPhotosIds.contains(element));
  151. selectedLocationPhotosIds
  152. .removeWhere((element) => selectedPhotosIds.contains(element));
  153. selectedPeoplePhotosIds
  154. .removeWhere((element) => selectedPhotosIds.contains(element));
  155. selectedBlurryPhotosIds
  156. .removeWhere((element) => selectedPhotosIds.contains(element));
  157. HomeController homeController = Get.find<HomeController>();
  158. if (homeController.locationPhoto.value != null &&
  159. selectedPhotosIds.contains(homeController.locationPhoto.value!.id)) {
  160. homeController.locationPhoto.value = null;
  161. if (locationPhotos.isNotEmpty) {
  162. var asset = locationPhotos.values.first.first;
  163. homeController.locationPhoto.value = asset;
  164. }
  165. }
  166. if (homeController.screenshotPhoto.value != null &&
  167. selectedPhotosIds.contains(homeController.screenshotPhoto.value!.id)) {
  168. homeController.screenshotPhoto.value = null;
  169. if (screenshotPhotos.isNotEmpty) {
  170. var asset = screenshotPhotos.first;
  171. homeController.screenshotPhoto.value = asset;
  172. }
  173. }
  174. if (homeController.blurryPhoto.value != null &&
  175. selectedPhotosIds.contains(homeController.blurryPhoto.value!.id)) {
  176. homeController.blurryPhoto.value = null;
  177. if (blurryPhotos.isNotEmpty) {
  178. var asset = blurryPhotos.first;
  179. homeController.blurryPhoto.value = asset;
  180. }
  181. }
  182. homeController.similarPhotos
  183. .removeWhere((element) => selectedPhotosIds.contains(element.id));
  184. if (homeController.locationPhoto.value != null &&
  185. selectedPhotosIds.contains(homeController.locationPhoto.value!.id)) {
  186. homeController.locationPhoto.value = null;
  187. }
  188. if (similarPhotos.isNotEmpty) {
  189. for (var group in ImagePickerUtil.similarPhotos) {
  190. for (var asset in group) {
  191. homeController.similarPhotos.add(asset);
  192. if (homeController.similarPhotos.length == 4) {
  193. break;
  194. }
  195. }
  196. }
  197. }
  198. homeController.peoplePhotos
  199. .removeWhere((element) => selectedPhotosIds.contains(element.id));
  200. if (peoplePhotos.isNotEmpty) {
  201. for (var personPhotos in peoplePhotos) {
  202. homeController.peoplePhotos.add(personPhotos);
  203. if (homeController.peoplePhotos.length == 2) {
  204. break;
  205. }
  206. }
  207. }
  208. debugPrint("ImagePickerUtil3 updatePhotoData $selectedPhotosIds");
  209. CalendarState.removePhotosData(selectedPhotosIds);
  210. }
  211. // 更新照片数据
  212. static Future<void> updatePhotos(
  213. List<Map<String, dynamic>> photoGroups) async {
  214. // clearAllPhotos();
  215. for (var group in photoGroups) {
  216. String type = group['type'] as String;
  217. Map<dynamic, dynamic> groupData = group['group'] as Map<dynamic, dynamic>;
  218. List<dynamic> photos = groupData['photos'] as List<dynamic>;
  219. int totalSize = groupData['totalSize'] as int;
  220. int count = groupData['count'] as int;
  221. switch (type) {
  222. case 'screenshots':
  223. screenshotPhotos.clear();
  224. screenshotPhotos.value = await _convertToAssetEntities(photos);
  225. screenshotsSize.value = totalSize;
  226. break;
  227. case 'similar':
  228. similarPhotos.add(await _convertToAssetEntities(photos));
  229. similarPhotosSize.value = totalSize;
  230. similarPhotoCount.value = count;
  231. break;
  232. case 'location':
  233. String location = group['name'] as String;
  234. locationPhotos[location] = await _convertToAssetEntities(photos);
  235. locationsSize.value = totalSize;
  236. break;
  237. case 'people':
  238. peoplePhotos.clear();
  239. peoplePhotos.value = await _convertToAssetEntities(photos);
  240. peopleSize.value = totalSize;
  241. break;
  242. case 'blurry':
  243. blurryPhotos.clear();
  244. blurryPhotos.value = await _convertToAssetEntities(photos);
  245. blurrySize.value = totalSize;
  246. break;
  247. }
  248. }
  249. }
  250. // 将原始照片数据转换为 AssetEntity 列表
  251. static Future<List<AssetEntity>> _convertToAssetEntities(
  252. List<dynamic> photos) async {
  253. List<AssetEntity> entities = [];
  254. for (var photo in photos) {
  255. final entity = await AssetEntity.fromId(photo['id'] as String);
  256. if (entity != null) {
  257. entities.add(entity);
  258. }
  259. }
  260. return entities;
  261. }
  262. //申请权限
  263. static Future<bool> requestPermissionExtend() async {
  264. final PermissionState ps = await PhotoManager.requestPermissionExtend(
  265. requestOption: const PermissionRequestOption(
  266. androidPermission: AndroidPermission(
  267. type: permissionType,
  268. mediaLocation: false,
  269. )));
  270. return ps.hasAccess;
  271. }
  272. //判断是否有权限
  273. static Future<bool> hasPermission() async {
  274. final PermissionState ps = await PhotoManager.getPermissionState(
  275. requestOption: const PermissionRequestOption(
  276. androidPermission: AndroidPermission(
  277. type: permissionType,
  278. mediaLocation: false,
  279. )));
  280. return ps.hasAccess;
  281. }
  282. static String formatFileSize(int bytes, {int decimals = 2}) {
  283. if (bytes <= 0) return '0 B';
  284. const suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];
  285. var i = (log(bytes) / log(1024)).floor();
  286. // 确保不超过数组范围
  287. i = i < suffixes.length ? i : suffixes.length - 1;
  288. // 计算实际大小
  289. final size = bytes / pow(1024, i);
  290. // 格式化数字,处理小数点位数
  291. String sizeStr;
  292. if (size >= 100) {
  293. // 大于100的只保留整数
  294. sizeStr = size.round().toString();
  295. } else {
  296. // 小于100的保留指定小数位
  297. sizeStr = size.toStringAsFixed(decimals);
  298. }
  299. // 移除末尾的0和不必要的小数点
  300. sizeStr = sizeStr.replaceAll(RegExp(r'\.?0+$'), '');
  301. return '$sizeStr ${suffixes[i]}';
  302. }
  303. /// 直接转换为 GB 单位
  304. static String formatToGB(int bytes, {int decimals = 2}) {
  305. if (bytes <= 0) return '0 GB';
  306. final gb = bytes / pow(1024, 3); // 直接转换为 GB
  307. // 格式化数字,处理小数点位数
  308. String sizeStr;
  309. if (gb >= 100) {
  310. // 大于100的只保留整数
  311. sizeStr = gb.round().toString();
  312. } else {
  313. // 小于100的保留指定小数位
  314. sizeStr = gb.toStringAsFixed(decimals);
  315. }
  316. // 移除末尾的0和不必要的小数点
  317. sizeStr = sizeStr.replaceAll(RegExp(r'\.?0+$'), '');
  318. return '$sizeStr GB';
  319. }
  320. /// 格式化存储大小
  321. static String formatSize(double sizeInGB) {
  322. if (sizeInGB < 0.001) {
  323. // 小于 1MB
  324. return '${(sizeInGB * 1024 * 1024).toStringAsFixed(1)} ';
  325. } else if (sizeInGB < 1) {
  326. // 小于 1GB
  327. return '${(sizeInGB * 1024).toStringAsFixed(1)} ';
  328. } else if (sizeInGB < 1024) {
  329. // 小于 1TB
  330. return '${sizeInGB.toStringAsFixed(1)} ';
  331. } else {
  332. // 大于等于 1TB
  333. return '${(sizeInGB / 1024).toStringAsFixed(1)} ';
  334. }
  335. }
  336. // 加载图片资源
  337. static Future<List<AssetEntity>> loadAssets({bool sortByDate = true}) async {
  338. final PermissionState result = await PhotoManager.requestPermissionExtend();
  339. if (!result.isAuth) return [];
  340. if (androidPhotos.isNotEmpty) return androidPhotos;
  341. // 选择相册
  342. final List<AssetPathEntity> albums = await PhotoManager.getAssetPathList(
  343. type: RequestType.common,
  344. filterOption: FilterOptionGroup(
  345. orders: [
  346. // 根据创建日期排序,降序(最新的在前)
  347. OrderOption(
  348. type: OrderOptionType.createDate,
  349. asc: !sortByDate, // 是否升序排列
  350. ),
  351. ],
  352. ),
  353. );
  354. int assetCount = await albums.first.assetCountAsync;
  355. debugPrint("ImagePickerUtil loadAssets assetCount $assetCount");
  356. androidPhotos = await albums.first.getAssetListPaged(
  357. page: 0,
  358. size: assetCount,
  359. );
  360. return androidPhotos;
  361. }
  362. }