iOS app调用相机和相册

首先导入两个协议 

UIImagePickerControllerDelegate

UINavigationControllerDelegate



实现下面两个方法 

-(void)takePhoto//打开相机

{

    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

        UIImagePickerController *picker = [[UIImagePickerController alloc]init];

        picker.delegate = self;

        picker.allowsEditing = YES;

        picker.sourceType = sourceType;

        [self presentViewController:picker animated:YES completion:nil];

    }

}


-(void)localPhoto//本地相册

{

    UIImagePickerController *picker = [[UIImagePickerController alloc]init];

    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    picker.delegate = self;

    picker.allowsEditing = YES;

    [self presentViewController:picker animated:YES completion:nil];

}


调用上面两个方法即可访问相机和相册


下面方法 获取 你选中的照片 或者 你拍下的照片

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

NSString *type = [info objectForKey:UIImagePickerControllerMediaType];

    if ([type isEqualToString:@"public.image"]) {

        //      把图片转化为NSData

        UIImage *image = info[UIImagePickerControllerEditedImage];

        NSData *data = UIImageJPEGRepresentation(image, 0.1);

    

       _userHead.image = image;

}

}


这样就可以把你的一个UIImageView设置为你刚拍的或者选择的照片了


你可能感兴趣的:(iOS)