//
// 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:@"保存图片结果提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
}
/*
*思路
*1.保存图片到相机胶卷
1>UIImageWriteToSavedPhotosAlbum函数
2>AssetsLibrary框架
3>Photos框架(推荐)
*2.拥有一个自定义相册
1> AssetsLibrary框架
2> Photos框架(推荐)
*3.将图片保存到自定义相册
1> AssetsLibrary框架
2> Photos框架(推荐)
*/
/*
*
Photos框架须知
1.PHAsset : 一个PHAsset对象代表一张图片或者一个视频文件
2.PHAssetCollection : 一个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中使用
文/OnlyChenJ(简书作者)
原文链接:http://www.jianshu.com/p/9c5f71759cfb
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
*
*
*/
- (IBAction)saveToNewThumb:(UIButton *)sender {
// 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;
}
});
}];
}
// 获得刚才添加到【相机胶卷】中的图片
-(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;
}
}
// 代码执行到这里,说明还没有自定义相册
__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];
// 保存结果
NSString *msg = nil ;
if(error){
msg = @"保存图片失败" ;
}else{
msg = @"保存图片成功" ;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示" message:msg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
}
@end
二 : 获取系统的相册图片(一张或者多张)
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];
});
}];
}
-(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];
}];
}
}