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