image_picker_util.dart 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import 'dart:io';
  2. import 'package:get/get.dart';
  3. import 'package:photo_manager/photo_manager.dart';
  4. class ImagePickerUtil {
  5. ImagePickerUtil._();
  6. static const RequestType permissionType = RequestType.image;
  7. // 全局存储不同类型的照片
  8. // 截图图片
  9. static final RxList<AssetEntity> screenshotPhotos = <AssetEntity>[].obs;
  10. // 相似图片
  11. static final RxList<List<AssetEntity>> similarPhotos = <List<AssetEntity>>[].obs;
  12. // 地点图片
  13. static final RxMap<String, List<AssetEntity>> locationPhotos = <String, List<AssetEntity>>{}.obs;
  14. // 人物图片
  15. static final RxList<AssetEntity> peoplePhotos = <AssetEntity>[].obs;
  16. // 清除所有照片数据
  17. static void clearAllPhotos() {
  18. screenshotPhotos.clear();
  19. similarPhotos.clear();
  20. locationPhotos.clear();
  21. peoplePhotos.clear();
  22. }
  23. // 更新照片数据
  24. static Future<void> updatePhotos(List<Map<String, dynamic>> photoGroups) async {
  25. clearAllPhotos();
  26. for (var group in photoGroups) {
  27. String type = group['type'] as String;
  28. List<dynamic> photos = group['group'] as List<dynamic>;
  29. switch (type) {
  30. case 'screenshots':
  31. screenshotPhotos.value = await _convertToAssetEntities(photos);
  32. break;
  33. case 'similar':
  34. similarPhotos.add(await _convertToAssetEntities(photos));
  35. break;
  36. case 'location':
  37. String location = group['name'] as String;
  38. locationPhotos[location] = await _convertToAssetEntities(photos);
  39. break;
  40. case 'people':
  41. peoplePhotos.value = await _convertToAssetEntities(photos);
  42. break;
  43. }
  44. }
  45. }
  46. // 将原始照片数据转换为 AssetEntity 列表
  47. static Future<List<AssetEntity>> _convertToAssetEntities(List<dynamic> photos) async {
  48. List<AssetEntity> entities = [];
  49. for (var photo in photos) {
  50. final entity = await AssetEntity.fromId(photo['id'] as String);
  51. if (entity != null) {
  52. entities.add(entity);
  53. }
  54. }
  55. return entities;
  56. }
  57. //申请权限
  58. static Future<bool> requestPermissionExtend() async {
  59. final PermissionState ps = await PhotoManager.requestPermissionExtend(
  60. requestOption: const PermissionRequestOption(
  61. androidPermission: AndroidPermission(
  62. type: permissionType,
  63. mediaLocation: false,
  64. )));
  65. return ps.hasAccess;
  66. }
  67. //判断是否有权限
  68. static Future<bool> hasPermission() async {
  69. final PermissionState ps = await PhotoManager.getPermissionState(
  70. requestOption: const PermissionRequestOption(
  71. androidPermission: AndroidPermission(
  72. type: permissionType,
  73. mediaLocation: false,
  74. )));
  75. return ps.hasAccess;
  76. }
  77. }