//创建一个相册控制器
UIImagePickerController *pc = [[UIImagePickerController alloc] init];
//图片来源
// UIImagePickerControllerSourceTypePhotoLibrary //相册库
// UIImagePickerControllerSourceTypeCamera //相机 (模拟器使用相机会崩溃,真机可以)
// UIImagePickerControllerSourceTypeSavedPhotosAlbum 照片库
pc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//是否允许编辑图片
pc.allowsEditing = YES;
pc.delegate = self; //设置代理 <UINavigationControllerDelegate,UIImagePickerControllerDelegate> //相册控制器要遵守两个协议
//把相册控制器 present 出来
[self presentViewController:pc animated:YES completion:nil];
相册代理里面可以设置
#pragma mark - 相册控制器的代理方法
//选择图片完成后调用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSLog(@"%@",info); //得到字典
//保存编辑后的图片 ,在字典里面有信息
self.imageView.image = info[@"UIImagePickerControllerEditedImage"];
// data 转成image
//UIImage imageWithData:<#(NSData *)#>
// image(.PNG) 转成data
//UIImagePNGRepresentation(<#UIImage *image#>)
// .jpg 转成data
//参数2. 压缩系数,0 - 1.0
NSData *dataOriginal = UIImageJPEGRepresentation(self.imageView.image, 1.0);
NSData *dataEdited = UIImageJPEGRepresentation(self.imageView.image, 0.3);
NSLog(@"%@",NSHomeDirectory());
//把原始的图片保存到沙盒
[dataOriginal writeToFile:[NSString stringWithFormat:@"%@/Library/1.jpg",NSHomeDirectory()] atomically:YES];
//把编辑过的图片也保存进去 方便对比 (编辑了会压缩,压缩过后的图片所占外存更小,放大会模糊)
[dataEdited writeToFile:[NSString stringWithFormat:@"%@/Library/2.jpg",NSHomeDirectory()] atomically:YES];
//返回
[picker dismissViewControllerAnimated:YES completion:nil];
}