以下内容是如何把APP中的图片保存到相册中和如何在相册中选取图片(一张或多张)
一: 把软件中的图片保存到系统相册或者保存到自己创建的相册中
方式一:
demo:
保存图片到系统相册,这只是简单的把图片保存到系统相册中,
Snip20160416_8.png
方式二:
保存图片到相册指定相册里,注意:其实只是把Camera Roll的相片又引用到了新的相册里
因为无论什么图片,都会首先保存在Camera Roll这个相册,之后根据自己的设置,才会保存
在指定的相册中
1>思路:
Snip20160416_9.png
2>思路步骤 :
1.添加图片到【相机胶卷】
1>UIImageWriteToSavedPhotosAlbum函数
2>AssetsLibrary框架
3>Photos框架(推荐)
2.拥有一个【自定义相册】
1>AssetsLibrary框架
2>Photos框架(推荐)
3.将刚才添加到【相机胶卷】的图片,引用(添加)到【自定义相册】
1>AssetsLibrary框架
2>Photos框架(推荐)
3>需要用到的框架,主要还是用到Photos框架,也是苹果自带的框架
Photos框架须知
1.PHAsset : 一个PHAsset对象代表一张图片或者一个视频文件
1> 负责查询一堆的PHAsset对象
2.PHAssetCollection :一个PHAssetCollection对象代表一个相册
1> 负责查询一堆的PHAssetCollection对象
3.PHAssetChangeRequest
1> 负责执行对PHAsset的【增删改】操作
2> 这个类只能放在
-[PHPhotoLibrary performChanges:completionHandler:]或者
-[PHPhotoLibrary performChangesAndWait:error:]方法的block中使用
4.PHAssetCollectionChangeRequest
1> 负责执行对PHAssetCollection的【增删改】操作
2> 这个类只能放在
-[PHPhotoLibrary performChanges:completionHandler:]或者
-[PHPhotoLibrary performChangesAndWait:error:]方法的block中使用
具体代码实现步骤:
demo:
导入框架
#import
以下总共抽取出来了三个方法,方便点击保存按钮时调用
// 获得刚才添加到【相机胶卷】中的图片-(PHFetchResult *)createdAssets{__blockNSString*createdAssetId =nil;// 添加图片到【相机胶卷】[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{ createdAssetId = [PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image].placeholderForCreatedAsset.localIdentifier;} error:nil];if(createdAssetId ==nil)returnnil;// 在保存完毕后取出图片return[PHAsset fetchAssetsWithLocalIdentifiers:@[createdAssetId] options:nil];}
获得【自定义相册】-(PHAssetCollection *)createdCollection{// 获取软件的名字作为相册的标题(如果需求不是要软件名称作为相册名字就可以自己把这里改成想要的名称)NSString*title = [NSBundlemainBundle].infoDictionary[(NSString*)kCFBundleNameKey];// 获得所有的自定义相册PHFetchResult *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];for(PHAssetCollection *collectionincollections) {if([collection.localizedTitleisEqualToString:title]) {returncollection; }}// 代码执行到这里,说明还没有自定义相册__blockNSString*createdCollectionId =nil;// 创建一个新的相册[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{ createdCollectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;} error:nil];if(createdCollectionId ==nil)returnnil;// 创建完毕后再取出相册return[PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createdCollectionId] options:nil].firstObject;}
//保存图片到相册-(void)saveImageIntoAlbum{// 获得相片PHFetchResult *createdAssets =self.createdAssets;// 获得相册PHAssetCollection *createdCollection =self.createdCollection;if(createdAssets ==nil|| createdCollection ==nil) { [SVProgressHUD showErrorWithStatus:@"保存失败!"];return;}// 将相片添加到相册NSError*error =nil;[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{ PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdCollection]; [request insertAssets:createdAssets atIndexes:[NSIndexSetindexSetWithIndex:0]];} error:&error];// 保存结果if(error) { [SVProgressHUD showErrorWithStatus:@"保存失败!"];}else{ [SVProgressHUD showSuccessWithStatus:@"保存成功!"];}}//点击保存按钮时调用-(IBAction)save {// requestAuthorization方法的功能1.如果用户还没有做过选择,这个方法就会弹框让用户做出选择1> 用户做出选择以后才会回调block2.如果用户之前已经做过选择,这个方法就不会再弹框,直接回调block,传递现在的授权状态给blockPHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {dispatch_async(dispatch_get_main_queue(), ^{switch(status) {casePHAuthorizationStatusAuthorized: {// 保存图片到相册[selfsaveImageIntoAlbum];break; }casePHAuthorizationStatusDenied: {if(oldStatus == PHAuthorizationStatusNotDetermined)return;NSLog(@"提醒用户打开相册的访问开关");break; }casePHAuthorizationStatusRestricted: { [SVProgressHUD showErrorWithStatus:@"因系统原因,无法访问相册!"];break; }default:break; } });}];
用户还没有对当前App授权过(用户从未点击过Don'tAllow或者OK按钮)PHAuthorizationStatusRestricted因为一些系统原因导致无法访问相册(比如家长控制)PHAuthorizationStatusDenied用户已经明显拒绝过当前App访问相片数据(用户已经点击过Don'tAllow按钮)PHAuthorizationStatusAuthorized用户已经允许过当前App访问相片数据(用户已经点击过OK按钮)
二 : 获取系统的相册图片(一张或者多张)
UIImagePickerControllerSourceTypePhotoLibrary, 从所有相册中选择图片UIImagePickerControllerSourceTypeCamera, 利用照相机拍一张图片(自定义照相机AVCaptureSession)UIImagePickerControllerSourceTypeSavedPhotosAlbum从Moments相册中选择图片
1.获取一张相册里的图片(图片 == 1)
获取相册中的图片
1.单张
1>UIImagePickerController
2>AssetsLibrary框架
3>Photos框架
2.多张(>=2张)
1>AssetsLibrary框架
2>Photos框架
demo1:
点击屏幕时,就跳转到系统相册进行选择图片(只能选择一张照片)
@interfaceViewController() -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event {UIImagePickerController*picker = [[UIImagePickerControlleralloc] init];picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;picker.delegate=self;[selfpresentViewController:picker animated:YEScompletion:nil];}
//实现代理方法-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{// 关闭选择图片界面[picker dismissViewControllerAnimated:YEScompletion:nil];// 获得选择的图片UIImageView*imageView = [[UIImageViewalloc] init];imageView.image= info[UIImagePickerControllerOriginalImage];imageView.frame=CGRectMake(0,0,100,100);[self.viewaddSubview:imageView];}-(void)imagePickerControllerDidCancel:(UIImagePickerController*)picker{// .....// 关闭选择图片界面[picker dismissViewControllerAnimated:YEScompletion:nil];}
2.获取多张相册里的图片(图片 >= 2)
用到框架和实现协议一些方法
demo2(部分重要代码):
#import"ViewController.h"#import#import-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event {[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){if(status != PHAuthorizationStatusAuthorized)return;dispatch_async(dispatch_get_main_queue(), ^{ CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init]; picker.delegate=self;// 显示选择的索引picker.showsSelectionIndex=YES;// 设置相册的类型:相机胶卷 + 自定义相册picker.assetCollectionSubtypes= @[ @(PHAssetCollectionSubtypeSmartAlbumUserLibrary), @(PHAssetCollectionSubtypeAlbumRegular)];// 不需要显示空的相册picker.showsEmptyAlbums=NO; [selfpresentViewController:picker animated:YEScompletion:nil]; });}];}
#pragma mark --(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset{NSIntegermax =2;if(picker.selectedAssets.count>= max) {UIAlertController*alert = [UIAlertControlleralertControllerWithTitle:@"提示"message:[NSStringstringWithFormat:@"最多选择%zd张图片", max] preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertActionactionWithTitle:@"好的"style:UIAlertActionStyleDefaulthandler:nil]]; [picker presentViewController:alert animated:YEScompletion:nil];// 这里不能使用self来modal别的控制器,因为此时self.view不在window上returnNO;}returnYES;}
-(void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray*)assets{// 关闭图片选择界面[picker dismissViewControllerAnimated:YEScompletion:nil];// 基本配置CGFloatscale = [UIScreenmainScreen].scale;PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];options.resizeMode= PHImageRequestOptionsResizeModeExact;options.deliveryMode= PHImageRequestOptionsDeliveryModeHighQualityFormat;// 遍历选择的所有图片for(NSIntegeri =0; i < assets.count; i++) { PHAsset *asset = assets[i];CGSizesize =CGSizeMake(asset.pixelWidth/ scale, asset.pixelHeight/ scale);// 获取图片[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage* _Nullable result,NSDictionary* _Nullable info) {UIImageView*imageView = [[UIImageViewalloc] init]; imageView.image= result; imageView.frame=CGRectMake((i %3) *110, (i /3) *110,100,100); [self.viewaddSubview:imageView]; }];}}
效果:
文/OnlyChenJ(简书作者)
原文链接:http://www.jianshu.com/p/9c5f71759cfb
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。