-
iOS獲取系統(tǒng)相冊(cè)圖片方法有三種:
UIImagePickerController,AssetsLibrary和Photos。
iOS 系統(tǒng)相冊(cè)
1. UIImagePickerController
- 這種方法比較簡(jiǎn)單,但靈活性差,我們直接看實(shí)例。
1.1 初始化控制器
UIImagePickerController *pickerCtr = [[UIImagePickerController alloc] init];
pickerCtr.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
pickerCtr.delegate = self;
1.2 打開相冊(cè)
[self presentViewController:pickerCtr animated:YES completion:nil];
1.3 選擇某個(gè)圖片時(shí)系統(tǒng)調(diào)用代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:@"public.image"]) {
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//process image
[picker dismissViewControllerAnimated:YES completion:nil];
}
}
1.4 取消選擇圖片時(shí)系統(tǒng)調(diào)用代理方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
2. AssetsLibrary(已經(jīng)在iOS8拋棄了)
- 這種方法比較高級(jí),自由性強(qiáng),基本滿足你所有操作,當(dāng)然不能滿足你也無(wú)能為力了,沒有其他方法了。
2.1導(dǎo)入頭文件
#import <AssetsLibrary/AssetsLibrary.h>
2.2創(chuàng)建AssetsLibrary對(duì)象并初始化
//在@interface中
@property (nonatomic, strong) ALAssetsLibrary *photoLibrary;
//在@implementation
- (ALAssetsLibrary *)photoLibrary {
if (!_photoLibrary) {
_photoLibrary = [[ALAssetsLibrary alloc] init];
}
return _photoLibrary;
}
2.3 獲取相冊(cè)圖片信息
- ALAssetsGroupType相冊(cè)類型
ALAssetsGroupLibrary NS_ENUM_DEPRECATED_IOS(4_0, 9_0) = (1 << 0), // The Library group that includes all assets.
ALAssetsGroupAlbum NS_ENUM_DEPRECATED_IOS(4_0, 9_0) = (1 << 1), // All the albums synced from iTunes or created on the device.
ALAssetsGroupEvent NS_ENUM_DEPRECATED_IOS(4_0, 9_0) = (1 << 2), // All the events synced from iTunes.
ALAssetsGroupFaces NS_ENUM_DEPRECATED_IOS(4_0, 9_0) = (1 << 3), // All the faces albums synced from iTunes.
ALAssetsGroupSavedPhotos NS_ENUM_DEPRECATED_IOS(4_0, 9_0) = (1 << 4), // The Saved Photos album.
#if __IPHONE_5_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
ALAssetsGroupPhotoStream NS_ENUM_DEPRECATED_IOS(5_0, 9_0) = (1 << 5), // The PhotoStream album.
#endif
ALAssetsGroupAll NS_ENUM_DEPRECATED_IOS(4_0, 9_0) = 0xFFFFFFFF, // The same as ORing together all the available group types,
- ALAssetsFilter相冊(cè)過濾器
//Get all photos assets in the assets group.
allPhotos;
// Get all video assets in the assets group.
allVideos;
// Get all assets in the group.
allAssets;
- group中獲取圖片方法
/**
@param NSIndexSet 需要獲取的相冊(cè)中圖片范圍
@param NSEnumerationOptions 獲取圖片的順序(順序還是逆序)
//ALAssetsGroupEnumerationResultsBlock的參數(shù)
@param result 照片ALAsset對(duì)象
@param index 當(dāng)前result在該group相冊(cè)中的位置,第index位置上
@param *stop 需要停止的時(shí)候 *stop = YES就停止繼續(xù)運(yùn)行當(dāng)前相冊(cè)group
*/
enumerateAssetsAtIndexes:(NSIndexSet *)indexSet options:(NSEnumerationOptions)options usingBlock:(ALAssetsGroupEnumerationResultsBlock)enumerationBlock
- ** 該開始獲取相冊(cè)圖片了**
- (void)getPhotoAlbumAsset {
[self.photoLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
//只讀圖片
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
//該相冊(cè)照片數(shù)量
NSInteger photoNumber = [group numberOfAssets];
NSIndexSet *IndexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, photoNumber)];
[group enumerateAssetsAtIndexes:IndexSet options:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
ALAssetRepresentation *representation = [result defaultRepresentation];
NSURL *photoUrl = [representation url];
NSDate *imageDate = [result valueForProperty:ALAssetPropertyDate];
//縮略圖
UIImage *image1 = [UIImage imageWithCGImage:result.thumbnail];
//屏幕分辨率圖
UIImage *image2 = [representation fullScreenImage];
//原圖
UIImage *image3 = [representation fullScreenImage];
}
}];
if (group == NULL) {
NSLog(@"讀取所有相冊(cè)結(jié)束");
}
} failureBlock:^(NSError *error) {
NSLog(@"獲取相冊(cè)圖片失敗");
}];
}
- 注意
- group為NULL時(shí),所有相冊(cè)都讀完了。
- 如果多次循環(huán)訪問
NSDictionary *metadata = [representation metadata]會(huì)內(nèi)存異常,原因是多次創(chuàng)建了metadata的字典,你的方法從當(dāng)前的runloop中返回前不會(huì)釋放內(nèi)存,因此內(nèi)存中加載了多個(gè)metadata。
解決方法如下,沒有對(duì)象持有metadata時(shí)被自動(dòng)釋放:
@autoreleasepool {
metadata = [representation metadata];
}
- 有些時(shí)候,先存儲(chǔ)圖片Url,需要的時(shí)候再讀圖片的需求,此時(shí)需要注意,這些Url只有在創(chuàng)建的
photoLibrary的生命周期內(nèi)有效,如果photoLibrary銷毀了獲取的Url也失效。
- 用Url獲取圖片方法
[self.photoLibrary assetForURL:photoUrl resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *representation = [result defaultRepresentation];
NSURL *photoUrl = [representation url];
//縮略圖
UIImage *image1 = [UIImage imageWithCGImage:result.thumbnail];
//屏幕分辨率圖
UIImage *image2 = [representation fullScreenImage];
//原圖
UIImage *image3 = [representation fullScreenImage];
} failureBlock:^(NSError *error) {
}];
3. Photos
-
Photos是iOS8之后支持的相冊(cè)訪問的庫(kù),蘋果重構(gòu)AssetsLibrary之后的產(chǎn)物。
3.1導(dǎo)入頭文件
#import <Photos/Photos.h>
3.2 設(shè)置需要檢索的相冊(cè)類型配置,需要照片或視頻在這里配置,或者隱藏的照片等等
PHFetchOptions *options = [PHFetchOptions new];
PHFetchResult *topLevelUserCollections = [PHAssetCollection fetchTopLevelUserCollectionsWithOptions:options];
PHAssetCollectionSubtype subType = PHAssetCollectionSubtypeAlbumRegular;
PHFetchResult *smartAlbumsResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum
subtype:subType
options:options];
3.3 遍歷出需要的相冊(cè)分類
NSMutableArray *photoGroups = [NSMutableArray array];
[topLevelUserCollections enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[PHAssetCollection class]]) {
PHAssetCollection *asset = (PHAssetCollection *)obj;
PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:asset options:[PHFetchOptions new]];
if (result.count > 0) {
PhotoAssetGroup *g = [PhotoAssetGroup groupWithName:asset.localizedTitle fetchResult:result];
[photoGroups addObject:g];
}
}
}];
[smartAlbumsResult enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:[PHAssetCollection class]]) {
PHAssetCollection *asset = (PHAssetCollection *)obj;
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:asset options:options];
if(result.count > 0 && asset.assetCollectionSubtype != PHAssetCollectionSubtypeSmartAlbumVideos) {
PhotoAssetGroup *g = [PhotoAssetGroup groupWithName:asset.localizedTitle fetchResult:result];
[photoGroups addObject:g];
}
}
}];
3.4 根據(jù)相冊(cè)分類查找所有照片信息
- (NSArray<PhotoAsset *> *)fetchPhotos:(NSArray<PhotoAssetGroup *> *)groups {
NSMutableArray *photoAssets = [NSMutableArray array];
for (PhotoAssetGroup *g in groups) {
__weak typeof(self)weakSelf = self;
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, g.result.count)];
[g.result enumerateObjectsAtIndexes:indexSet options:NSEnumerationReverse usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
PHAsset *asset = (PHAsset*)obj;
if (asset.mediaType == PHAssetMediaTypeImage) {
if (![weakSelf.imageProcessor checkAlreadyProcessed:asset.localIdentifier]) {
PhotoAsset *pAsset = [PhotoAsset assetWthLocaleIdentifier:asset.localIdentifier creationDate:asset.creationDate];
if (![photoAssets containsObject:pAsset]) {
[photoAssets addObject:pAsset];
}
}
}
}];
}
[photoAssets sortWithOptions:NSSortStable usingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
PhotoAsset *asset1 = obj1;
PhotoAsset *asset2 = obj2;
return ([asset1.creationDate compare:asset2.creationDate] == NSOrderedAscending);
}];
return photoAssets;
}
3.5 PhotoAsset和PhotoAssetGroup為自定義類
@interface PhotoAsset : NSObject
@property (nonatomic, copy, readonly) NSString *localIdentifier;
@property (nonatomic, strong) NSDate *creationDate;
- (PhotoAsset *)initWithLocaleIdentifier:(NSString *)identifier creationDate:(NSDate *)date;
+ (PhotoAsset *)assetWthLocaleIdentifier:(NSString *)identifier creationDate:(NSDate *)date;
@end
@interface PhotoAssetGroup : NSObject
@property (nonatomic, copy) NSString *groupName;
@property (nonatomic, strong) PHFetchResult *result;
- (PhotoAssetGroup *)initWithName:(NSString *)name fetchResult:(PHFetchResult *)result;
+ (PhotoAssetGroup *)groupWithName:(NSString *)name fetchResult:(PHFetchResult *)result;
@end
- 如果文章對(duì)你有幫助,請(qǐng)點(diǎn)下“喜歡”吧,感謝!
