要将图片保存至系统相册,首先要获取相册访问和读写权限,在info.plist文件中添加两个字段,描述获取相册的目的
Privacy - Photo Library Additions Usage Description
Privacy - Photo Library Usage Description
保存到相册有两种方式,第一种方式不会创建相薄,保存在所有照片中
//screenImg 要保存的图片对象
UIImageWriteToSavedPhotosAlbum(screenImg, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
if (error == nil) {
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"已保存至手机相册" preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alertView animated:YES completion:nil];
double delayInSeconds = 1.2;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[alertView dismissViewControllerAnimated:YES completion:nil];
});
}else{
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"保存失败" preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alertView animated:YES completion:nil];
double delayInSeconds = 1.2;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[alertView dismissViewControllerAnimated:YES completion:nil];
});
}
}
第二种方式,使用Photos框架存储图片至相册,首先#import <Photos/Photos.h>
//1.判断用户相册的写入权限
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusNotDetermined) {
//2.若用户未对权限请求做出选择,则请求权限
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
switch (status) {
case PHAuthorizationStatusAuthorized:
//已获取权限,保存图片到相册
[self saveImageToPhotoLibrary:screenImg];
break;
case PHAuthorizationStatusDenied:
//已被用户拒绝获取权限
break;
case PHAuthorizationStatusRestricted:
//没有权限访问照片
break;
case PHAuthorizationStatusNotDetermined:
//用户尚未对权限访问做出选择
break;
default:
break;
}
}];
} else if (status == PHAuthorizationStatusAuthorized) {
//已获取权限,保存图片到相册
[self saveImageToPhotoLibrary:screenImg];
} else {
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"未获取权限" message:@"请在设置界面->隐私->照片 为本应用打开权限" preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alertView animated:YES completion:nil];
double delayInSeconds = 1.2;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[alertView dismissViewControllerAnimated:YES completion:nil];
});
}
- (void)saveImageToPhotoLibrary:(UIImage *)screenImg {
//3.判断或创建相册并存储图片
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// 判断系统相册中是否已经有该名称相册
PHAssetCollection *assetCollection = [self fetchAssetColletion:@"TestImage"];
//创建一个操作图库的对象
PHAssetCollectionChangeRequest *collectionChangeRequest;
if (assetCollection) {
//如果已经有了,操作对象就是该相册,图片将存入该相册
collectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
} else {
//如果没有该相册,则创建一个相册
collectionChangeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"TestImage"];
}
//存储图片
PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:screenImg];
//使用占位图片先占用一个内存,有图片的时候将图片存入该内存
PHObjectPlaceholder *placeholder = [assetChangeRequest placeholderForCreatedAsset];
[collectionChangeRequest addAssets:@[placeholder]];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (error) {
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"保存失败" preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alertView animated:YES completion:nil];
double delayInSeconds = 1.2;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[alertView dismissViewControllerAnimated:YES completion:nil];
});
} else {
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"保存成功" preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alertView animated:YES completion:nil];
double delayInSeconds = 1.2;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[alertView dismissViewControllerAnimated:YES completion:nil];
});
}
}];
}
- (PHAssetCollection *)fetchAssetColletion:(NSString *)albumTitle {
//获取所有相册
PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
//遍历判断是否存在该相册
for (PHAssetCollection *collection in result) {
if ([collection.localizedTitle isEqualToString:albumTitle]) {
return collection;
}
}
return nil;
}
如果不需要将图片保存至相册,只是临时使用的话,将图片缓存至本地沙盒文件就可以了
//UIImagePNGRepresentation 将图片处理成png格式,质量较高,图片也占用内存较大
//UIImageJPEGRepresentation 将图片处理成jpg格式,第二个参数为图片的失真率,值在0-1之间,值越小则图片占用内存就越小,图片的视觉效果不受影响
NSString *pathHome = NSHomeDirectory();
//设置一个图片的存储路径
NSString *imagePath = [pathHome stringByAppendingString:@"/Library/Caches/screenShot.jpg"];
//把图片直接保存到指定的路径(同时应该把图片的路径imagePath存起来,下次就可以直接用来取图片)
[UIImageJPEGRepresentation(screenImg, 1.0) writeToFile:imagePath atomically:YES];
NSLog(@"%@", [UIImage imageWithContentsOfFile:imagePath]);