iOS保存(獲取)圖片到相冊

iOS保存圖片到相冊

//
//  ViewController.m
//  thumbDemo
//
//  Created by qianfeng on 16/11/28.
//  Copyright ? 2016年 qianfeng. All rights reserved.
//

#import "ViewController.h"
#import <Photos/Photos.h>

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;

//
@property(strong,nonatomic) UIImage *image;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.image = [UIImage imageNamed:@"QQ圖片20161113174556"];
    
    self.iconImageView.image = self.image;
    
    
}

//保存到相冊
- (IBAction)saveToThumb:(UIButton *)sender {
    UIImageWriteToSavedPhotosAlbum(self.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
}
-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *msg = nil ;
    if(error){
        msg = @"保存圖片失敗" ;
     }else{
        msg = @"保存圖片成功" ;
     }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存圖片結(jié)果提示"        message:msg delegate:self  cancelButtonTitle:@"確定" otherButtonTitles:nil];
    [alert show];
}







/*
 *思路
 *1.保存圖片到相機膠卷
       1>UIImageWriteToSavedPhotosAlbum函數(shù)
       2>AssetsLibrary框架
       3>Photos框架(推薦)
 *2.擁有一個自定義相冊
       1> AssetsLibrary框架
       2> Photos框架(推薦)
 *3.將圖片保存到自定義相冊
       1> AssetsLibrary框架
       2> Photos框架(推薦)
 */



/*
 *
 Photos框架須知
 
 1.PHAsset : 一個PHAsset對象代表一張圖片或者一個視頻文件
 
 2.PHAssetCollection : 一個PHAssetCollection對象代表一個相冊
 
 3.PHAssetChangeRequest
 1> 負責執(zhí)行對PHAsset的【增刪改】操作
 2> 這個類只能放在
 -[PHPhotoLibrary performChanges:completionHandler:]或者
 -[PHPhotoLibrary performChangesAndWait:error:]方法的block中使用
 
 4.PHAssetCollectionChangeRequest
 1> 負責執(zhí)行對PHAssetCollection的【增刪改】操作
 2> 這個類只能放在
 -[PHPhotoLibrary performChanges:completionHandler:] 或者
 -[PHPhotoLibrary performChangesAndWait:error:]方法的block中使用
 
 文/OnlyChenJ(簡書作者)
 原文鏈接:http://www.reibang.com/p/9c5f71759cfb
 著作權(quán)歸作者所有辨绊,轉(zhuǎn)載請聯(lián)系作者獲得授權(quán)争群,并標注“簡書作者”媚朦。
 *
 *
 */
- (IBAction)saveToNewThumb:(UIButton *)sender {
    // requestAuthorization方法的功能
    //    1.如果用戶還沒有做過選擇熙揍,這個方法就會彈框讓用戶做出選擇
    //    1> 用戶做出選擇以后才會回調(diào)block
    //    2.如果用戶之前已經(jīng)做過選擇斩郎,這個方法就不會再彈框悉稠,直接回調(diào)block实蓬,傳遞現(xiàn)在的授權(quán)狀態(tài)給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(@"提醒用戶打開相冊的訪問開關(guān)");
                    break;
                }
                case PHAuthorizationStatusRestricted: {
                    //   [SVProgressHUD showErrorWithStatus:@"因系統(tǒng)原因,無法訪問相冊全谤!"];
                    break;
                }
                default:
                    break;
            }
        });
    }];

    
}

// 獲得剛才添加到【相機膠卷】中的圖片
-(PHFetchResult<PHAsset *> *)createdAssets
{
    __block NSString *createdAssetId = nil;
    // 添加圖片到【相機膠卷】
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        createdAssetId = [PHAssetChangeRequest creationRequestForAssetFromImage:self.iconImageView.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;
        }
    }
    // 代碼執(zhí)行到這里肤晓,說明還沒有自定義相冊
    __block NSString *createdCollectionId = nil;
    // 創(chuàng)建一個新的相冊
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        createdCollectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
    } error:nil];
    if (createdCollectionId == nil) return nil;
    // 創(chuàng)建完畢后再取出相冊
    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];
    // 保存結(jié)果
    NSString *msg = nil ;
    if(error){
        msg = @"保存圖片失敗" ;
    }else{
        msg = @"保存圖片成功" ;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存圖片結(jié)果提示"        message:msg delegate:self  cancelButtonTitle:@"確定" otherButtonTitles:nil];
    [alert show];
}
@end

二 : 獲取系統(tǒng)的相冊圖片(一張或者多張)

UIImagePickerControllerSourceTypePhotoLibrary, 從所有相冊中選擇圖片
UIImagePickerControllerSourceTypeCamera, 利用照相機拍一張圖片(自定義照相機AVCaptureSession)
UIImagePickerControllerSourceTypeSavedPhotosAlbum 從Moments相冊中選擇圖片
1.獲取一張相冊里的圖片(圖片 == 1)

獲取相冊中的圖片

1.單張
1> UIImagePickerController(推薦)
2> AssetsLibrary框架
3> Photos框架

2.多張(>=2張)
1> AssetsLibrary框架
2> Photos框架(推薦)

demo1

點擊屏幕時,就跳轉(zhuǎn)到系統(tǒng)相冊進行選擇圖片(只能選擇一張照片)

@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];
}

代理方法

//實現(xiàn)代理方法<UIImagePickerControllerDelegate>
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
// 關(guān)閉選擇圖片界面
[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
{
// .....
// 關(guān)閉選擇圖片界面
[picker dismissViewControllerAnimated:YES completion:nil];
}
2.獲取多張相冊里的圖片(圖片 >= 2)

用到框架和實現(xiàn)協(xié)議一些方法

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;
      // 設(shè)置相冊的類型:相機膠卷 + 自定義相冊
      picker.assetCollectionSubtypes = @[
        @(PHAssetCollectionSubtypeSmartAlbumUserLibrary),
        @(PHAssetCollectionSubtypeAlbumRegular)];
      // 不需要顯示空的相冊
      picker.showsEmptyAlbums = NO;
      [self presentViewController:picker animated:YES completion:nil];
  });
}];
}
-(void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
// 關(guān)閉圖片選擇界面
[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];
  }];
}
}
效果:
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末补憾,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子卷员,更是在濱河造成了極大的恐慌盈匾,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,378評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件子刮,死亡現(xiàn)場離奇詭異,居然都是意外死亡窑睁,警方通過查閱死者的電腦和手機挺峡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,970評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來担钮,“玉大人橱赠,你說我怎么就攤上這事◇锝颍” “怎么了狭姨?”我有些...
    開封第一講書人閱讀 168,983評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長苏遥。 經(jīng)常有香客問我饼拍,道長,這世上最難降的妖魔是什么田炭? 我笑而不...
    開封第一講書人閱讀 59,938評論 1 299
  • 正文 為了忘掉前任师抄,我火速辦了婚禮,結(jié)果婚禮上教硫,老公的妹妹穿的比我還像新娘叨吮。我一直安慰自己,他們只是感情好瞬矩,可當我...
    茶點故事閱讀 68,955評論 6 398
  • 文/花漫 我一把揭開白布茶鉴。 她就那樣靜靜地躺著,像睡著了一般景用。 火紅的嫁衣襯著肌膚如雪涵叮。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,549評論 1 312
  • 那天,我揣著相機與錄音围肥,去河邊找鬼剿干。 笑死,一個胖子當著我的面吹牛穆刻,可吹牛的內(nèi)容都是我干的置尔。 我是一名探鬼主播,決...
    沈念sama閱讀 41,063評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼氢伟,長吁一口氣:“原來是場噩夢啊……” “哼榜轿!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起朵锣,我...
    開封第一講書人閱讀 39,991評論 0 277
  • 序言:老撾萬榮一對情侶失蹤谬盐,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后诚些,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體飞傀,經(jīng)...
    沈念sama閱讀 46,522評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,604評論 3 342
  • 正文 我和宋清朗相戀三年诬烹,在試婚紗的時候發(fā)現(xiàn)自己被綠了砸烦。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,742評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡绞吁,死狀恐怖幢痘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情家破,我是刑警寧澤颜说,帶...
    沈念sama閱讀 36,413評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站汰聋,受9級特大地震影響门粪,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜烹困,卻給世界環(huán)境...
    茶點故事閱讀 42,094評論 3 335
  • 文/蒙蒙 一庄拇、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧韭邓,春花似錦措近、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,572評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至鸭你,卻和暖如春屈张,著一層夾襖步出監(jiān)牢的瞬間擒权,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,671評論 1 274
  • 我被黑心中介騙來泰國打工阁谆, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留碳抄,地道東北人。 一個月前我還...
    沈念sama閱讀 49,159評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親围详。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,747評論 2 361

推薦閱讀更多精彩內(nèi)容