访问相机相册用的都是 UIImagePickerController
相关权限问题:
//首先需要导入头文件: #import
// 判断是够有全向访问相机
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
{
//无权限
NSLog(@"没有访问相机权限");
return;
}else{
}
//首先需要导入头文件: #import
// 判断是否有访问相册的权限
PHAuthorizationStatus author = [PHPhotoLibrary authorizationStatus];
if (author == PHAuthorizationStatusRestricted || author ==PHAuthorizationStatusDenied){
//无权限
NSLog(@"没有访问相册的权限");
return;
}else{
}
调用相机相册的操作:(根据sourcetype的类型判断是调用相机还是相册)
// sourceType的枚举类型
// UIImagePickerControllerSourceTypePhotoLibrary, 从所有相册中选择图片或视频
// UIImagePickerControllerSourceTypeCamera, 利用照相机拍一张图片或视频
// UIImagePickerControllerSourceTypeSavedPhotosAlbum 从Moments相册中选择图片或视频
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.allowsEditing = YES;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:imagePicker animated:YES completion:nil];
通过相机或者相册操作选取图片后调用的代理:
#pragma mark - UIImagePickerControllerDelegate
// 完成图片的选取后调用的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// 选取完图片后跳转回原控制器
[picker dismissViewControllerAnimated:YES completion:nil];
/* 此处参数 info 是一个字典,下面是字典中的键值 (从相机获取的图片和相册获取的图片时,两者的info值不尽相同)
* UIImagePickerControllerMediaType; // 媒体类型
* UIImagePickerControllerOriginalImage; // 原始图片
* UIImagePickerControllerEditedImage; // 裁剪后图片
* UIImagePickerControllerCropRect; // 图片裁剪区域(CGRect)
* UIImagePickerControllerMediaURL; // 媒体的URL
* UIImagePickerControllerReferenceURL // 原件的URL
* UIImagePickerControllerMediaMetadata // 当数据来源是相机时,此值才有效
*/
// 从info中将图片取出,并加载到imageView当中
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
self.imageView.image = image;
//将获得的图片保存到系统相册的方法
// 创建保存图像时需要传入的选择器对象(回调方法格式固定)
SEL selector = @selector(image:didFinishSavingWithError:contextInfo:);
// 将图像保存到相册(第三个参数需要传入上面格式的选择器对象)
UIImageWriteToSavedPhotosAlbum(image, self, selector, NULL);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contentInfo{
if (!error) {
NSLog(@"保存图片成功");
}else{
NSLog(@"Error:%@", error);
}
}