IOS-照相,相片选取

初始化

 UIImagePickerControllerSourceType sourceType;
        switch (buttonIndex)
        {
            case 0:

                sourceType = UIImagePickerControllerSourceTypeCamera;
                if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
                {
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                }
                break;
            default:
                sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
                break;
        }


        NSString *mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];

        if(authStatus ==AVAuthorizationStatusRestricted){//此应用程序没有被授权访问的照片数据。可能是家长控制权限。

        }else if(authStatus == AVAuthorizationStatusDenied){// 用户已经明确否认了这一照片数据的应用程序访问
            [self showAlertView:@"热波间需要访问你的相机" message:@"头像修改,热波间需要访问你的相机权限。点击“设置”前往系统设置允许热波间访问你的相机" confirm:^(id sender) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

            } cancel:^(id sender) {

            }];
            return;
        }
        else if(authStatus == AVAuthorizationStatusAuthorized){//用户已授权应用访问照片数据.

            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            picker.mediaTypes = @[(NSString *) kUTTypeImage];
            [self presentViewController:picker animated:YES completion:nil];

        }else if(authStatus == AVAuthorizationStatusNotDetermined){// 用户尚未做出了选择这个应用程序的问候.一次一出现

            [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {//弹出授权弹框
                if(granted){//点击允许访问时调用
                            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                            picker.delegate = self;
                            picker.allowsEditing = YES;
                            picker.sourceType = sourceType;
                            picker.mediaTypes = @[(NSString *) kUTTypeImage];
                            [self presentViewController:picker animated:YES completion:nil];
                }
                else {
                    return ;
                }

            }];
        }else {
            NSLog(@"Unknown authorization status");
        }

Delegate

#pragma mark UIImagePickerController Delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:@"public.image"])
    {
        MBProgressHUD *mbProgressHud = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:mbProgressHud];
        [mbProgressHud show:YES];

        //[info objectForKey:@"UIImagePickerControllerEditedImage"];
        NSString *tempDir = NSTemporaryDirectory ();
        NSString *tempFile = [NSString stringWithFormat:@"%@/avatar.png",tempDir];
        UIImage *avatar = [info objectForKey:@"UIImagePickerControllerEditedImage"];


        float scale = MAX(avatar.size.width/150,avatar.size.height/150);
        avatar = [UIImage imageWithCGImage:avatar.CGImage scale:scale orientation:UIImageOrientationUp];
        [UIImagePNGRepresentation(avatar) writeToFile:tempFile atomically:YES];

        __weak typeof(self) weakSelf = self;
        updateCurrUserModel *userModel = [[updateCurrUserModel alloc] init];
        [userModel uploadDataWithFileUrl:tempFile params:nil success:^(id object) {
            __strong typeof(self) strongSelf = weakSelf;
            if (strongSelf)
            {
                /*成功返回数据*/
                if (userModel.result == 0)
                {
                    strongSelf.selectedImg = avatar;
                    strongSelf.headImgView.image = avatar;
                    strongSelf.userInfo.photo = userModel.data;
                    float quality = .00001f;
                    float blurred = .2f;
                    NSData *imageData = UIImageJPEGRepresentation([strongSelf.headImgView image], quality);
                    UIImage *blurredImage = [[UIImage imageWithData:imageData] blurredImage:blurred];
                    _backImageView.image = blurredImage;
                    [UserInfoManager shareUserInfoManager].currentUserInfo.photo = userModel.data;

                    NSError *error;
                    [[NSFileManager defaultManager] removeItemAtPath:tempFile error:&error];
                }
            }
            [mbProgressHud hide:YES];

        } fail:^(id object) {
            /*失败返回数据*/
            [mbProgressHud hide:YES];
            [self showNoticeInWindow:@"网络连接失败,请重试" duration:1.5];
        }];

    }

    [picker dismissViewControllerAnimated:YES completion:nil];
}

图片裁剪

获取到图片后反转

//压缩图片  
- (UIImage *)image:(UIImage*)image scaledToSize:(CGSize)newSize  
{  
    // Create a graphics image context  
    UIGraphicsBeginImageContext(newSize);  
    // Tell the old image to draw in this new context, with the desired  
    // new size  
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];  
    // Get the new image from the context  
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();  
    // End the context  
    UIGraphicsEndImageContext();  
    // Return the new image.  
    return newImage;  
}  

方法2

//裁剪图片  
- (UIImage *)cutImage:(UIImage*)image  
{  
    //压缩图片  
    CGSize newSize;  
    CGImageRef imageRef = nil;  

    if ((image.size.width / image.size.height) < (_headerView.bgImgView.size.width / _headerView.bgImgView.size.height)) {  
        newSize.width = image.size.width;  
        newSize.height = image.size.width * _headerView.bgImgView.size.height / _headerView.bgImgView.size.width;  

        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));  

    } else {  
        newSize.height = image.size.height;  
        newSize.width = image.size.height * _headerView.bgImgView.size.width / _headerView.bgImgView.size.height;  

        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));  

    }  

    return [UIImage imageWithCGImage:imageRef];  
}
权限问题 pod TZImageManager
#pragma mark - UIImagePickerController

- (void)takePhoto {



    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
        // 拍照之前还需要检查相册权限
    }
        else if ([TZImageManager  authorizationStatus] == 2) { // 已被拒绝,没有相册权限,将无法保存拍的照片
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            alert.tag = 1;
            [alert show];
        } else if ([TZImageManager  authorizationStatus] == 0) { // 正在弹框询问用户是否允许访问相册,监听权限状态
            [[TZImageManager manager]requestAuthorizationWithCompletion:^{
                return [self takePhoto];

            }];
        }
    else { // 调用相机
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            if(iOS8Later) {
                _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            }
            [self presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值