iOS之保存图片到系统相册和从系统相册选取一张或者多张照片

假装没事ソ 提交于 2020-03-14 07:53:56

以下内容是如何把APP中的图片保存到相册中和如何在相册中选取图片(一张或多张)

一: 把软件中的图片保存到系统相册或者保存到自己创建的相册中

方式一:
demo:

保存图片到系统相册,这只是简单的把图片保存到系统相册中

传入博客的参考图片加载不出来,请参考OnlyChenJ的简书


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 <Photos/Photos.h>
        以下总共抽取出来了三个方法,方便点击保存按钮时调用

        // 获得刚才添加到【相机胶卷】中的图片 
        -(PHFetchResult<PHAsset *> *)createdAssets
        {
        __block NSString *createdAssetId = nil;
        // 添加图片到【相机胶卷】
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
         createdAssetId = [PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image].placeholderForCreatedAsset.localIdentifier;
        } error:nil];
        if (createdAssetId == nil) return nil;
        // 在保存完毕后取出图片
        return [PHAsset fetchAssetsWithLocalIdentifiers:@[createdAssetId] options:nil];
        }
        获得【自定义相册】
        -(PHAssetCollection *)createdCollection
        {
        // 获取软件的名字作为相册的标题(如果需求不是要软件名称作为相册名字就可以自己把这里改成想要的名称)
        NSString *title = [NSBundle mainBundle].infoDictionary[(NSString *)kCFBundleNameKey];   
        // 获得所有的自定义相册
        PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
        for (PHAssetCollection *collection in collections) {
         if ([collection.localizedTitle isEqualToString:title]) {
             return collection;
         }
        }
        // 代码执行到这里,说明还没有自定义相册
        __block NSString *createdCollectionId = nil;
        // 创建一个新的相册
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
         createdCollectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
        } error:nil];
        if (createdCollectionId == nil) return nil;
        // 创建完毕后再取出相册
        return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createdCollectionId] options:nil].firstObject;
        }
        //保存图片到相册
        -(void)saveImageIntoAlbum
        {
        // 获得相片
        PHFetchResult<PHAsset *> *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:[NSIndexSet indexSetWithIndex:0]];
        } error:&error];
        // 保存结果
        if (error) {
         [SVProgressHUD showErrorWithStatus:@"保存失败!"];
        } else {
         [SVProgressHUD showSuccessWithStatus:@"保存成功!"];
        }
        }
        //点击保存按钮时调用
        -(IBAction)save {
        // requestAuthorization方法的功能
        1.如果用户还没有做过选择,这个方法就会弹框让用户做出选择
        1> 用户做出选择以后才会回调block
        2.如果用户之前已经做过选择,这个方法就不会再弹框,直接回调block,传递现在的授权状态给block
        PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
         dispatch_async(dispatch_get_main_queue(), ^{
             switch (status) {
                 case PHAuthorizationStatusAuthorized: {
                     //  保存图片到相册
                     [self saveImageIntoAlbum];
                     break;
                 } 
                 case PHAuthorizationStatusDenied: {
                     if (oldStatus == PHAuthorizationStatusNotDetermined) return;
                     NSLog(@"提醒用户打开相册的访问开关");
                     break;
                 }       
                 case PHAuthorizationStatusRestricted: {
                     [SVProgressHUD showErrorWithStatus:@"因系统原因,无法访问相册!"];
                     break;
                 }       
                 default:
                     break;
             }
         });
        }];
        用户还没有对当前App授权过(用户从未点击过Don't Allow或者OK按钮)
        PHAuthorizationStatusRestricted
        因为一些系统原因导致无法访问相册(比如家长控制)
        PHAuthorizationStatusDenied
        用户已经明显拒绝过当前App访问相片数据(用户已经点击过Don't Allow按钮)
        PHAuthorizationStatusAuthorized
        用户已经允许过当前App访问相片数据(用户已经点击过OK按钮)

二 : 获取系统的相册图片(一张或者多张)

UIImagePickerControllerSourceTypePhotoLibrary, 从所有相册中选择图片
UIImagePickerControllerSourceTypeCamera, 利用照相机拍一张图片(自定义照相机AVCaptureSession)
UIImagePickerControllerSourceTypeSavedPhotosAlbum 从Moments相册中选择图片
1.获取一张相册里的图片(图片 == 1)

获取相册中的图片

  • 1.单张
    1> UIImagePickerController
    2> AssetsLibrary框架
    3> Photos框架

    • 2.多张(>=2张)
      1> AssetsLibrary框架
      2> Photos框架
      demo1:
    • 点击屏幕时,就跳转到系统相册进行选择图片(只能选择一张照片)
      @interface ViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITableViewDelegate>
      -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
      UIImagePickerController *picker = [[UIImagePickerController alloc] init];
      picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
      picker.delegate = self;
      [self presentViewController:picker animated:YES completion:nil];
      }
      //实现代理方法<UIImagePickerControllerDelegate>
      -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
      {
      // 关闭选择图片界面
      [picker dismissViewControllerAnimated:YES completion:nil];
      // 获得选择的图片
      UIImageView *imageView = [[UIImageView alloc] init];
      imageView.image = info[UIImagePickerControllerOriginalImage];
      imageView.frame = CGRectMake(0, 0, 100, 100);
      [self.view addSubview:imageView];
      }
      -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
      {
      // .....
      // 关闭选择图片界面
      [picker dismissViewControllerAnimated:YES completion:nil];
      }
      2.获取多张相册里的图片(图片 >= 2)
      用到框架和实现协议一些方法
      demo2(部分重要代码):
      #import "ViewController.h"
      #import <Photos/Photos.h>
      #import <CTAssetsPickerController/CTAssetsPickerController.h>
      -(void)touchesBegan:(NSSet<UITouch *> *)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;
            [self presentViewController:picker animated:YES completion:nil];
        });
      }];
      }
      #pragma mark - <CTAssetsPickerControllerDelegate>
      -(BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
      {
      NSInteger max = 2;  
      if (picker.selectedAssets.count >= max) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"最多选择%zd张图片", max] preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil]];
        [picker presentViewController:alert animated:YES completion:nil];
        // 这里不能使用self来modal别的控制器,因为此时self.view不在window上
        return NO;
      }
      return YES;
      }
      -(void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
      {
      // 关闭图片选择界面
      [picker dismissViewControllerAnimated:YES completion:nil];
      // 基本配置
      CGFloat scale = [UIScreen mainScreen].scale;
      PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
      options.resizeMode   = PHImageRequestOptionsResizeModeExact;
      options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
      // 遍历选择的所有图片
      for (NSInteger i = 0; i < assets.count; i++) {
        PHAsset *asset = assets[i];
        CGSize size = 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 = [[UIImageView alloc] init];
            imageView.image = result;
            imageView.frame = CGRectMake((i % 3) * 110, (i / 3) * 110, 100, 100);
            [self.view addSubview:imageView];
        }];
      }
      }
      效果:
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!