如何在启用ARC的情况下检索使用UIImagePickerControllerDelegate拍摄的图像?

时间:2013-12-10 09:32:24

标签: ios objective-c

我有一个应用程序,需要拍照,然后显示给用户。我打开相机让用户使用以下代码拍照:

if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType =
    UIImagePickerControllerSourceTypeCamera;
    imagePicker.mediaTypes = @[(NSString *) kUTTypeImage];
    imagePicker.allowsEditing = NO;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;

    [self presentViewController:imagePicker animated:YES completion:nil];
} else {
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle: @"Camera failed to open"
                          message: @"Camera is not available"
                          delegate: nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil];
    [alert show];
}

这显示相机视图,以便用户可以拍照。我实现了处理取消和完成事件的方法,如下所示:

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

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

    [self dismissViewControllerAnimated:YES completion:nil];

    UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
    [photoView setImage:image];
    [photoView setNeedsDisplay];
}

问题是经过最后一个函数后,图像为零。起初,dismissViewControllerAnimated位于函数的末尾,但是在this SO post中,答案解释了应首先调用dismissViewControllerAnimated,并且应该在从info获取图像之前释放picker。我尝试将dismissViewControllerAnimated放在顶部,但因为我使用ARC我无法释放选择器。

如何从信息中获取图像?

3 个答案:

答案 0 :(得分:1)

试试这个:

UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
// or UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];

答案 1 :(得分:1)

您已在代码中设置picker.allowsEditing = NO;。那你为什么要检索编辑过的图像?它不会存在。无论如何,如果你允许编辑,请使用:

photoView.image = info[UIImagePickerControllerEditedImage] ? info[UIImagePickerControllerEditedImage] : info[UIImagePickerControllerOriginalImage]

如果用户编辑了照片,则photoView.image将设置为已编辑的照片,否则将设置为原始照片。

如果您不允许编辑,只需使用UIImagePickerControllerOriginalImage键检索图像。

答案 2 :(得分:-1)

检查此方法,

 (void) imagePickerController:(UIImagePickerController *)_picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
      NSLog(@"dictionary image info: %@",info );
    }

在此方法中,打印字典并检查您是否获得 UIImagePickerControllerMediaType UIImagePickerControllerOriginalImage 。 (就我而言,我得到的价值就像这样 UIImagePickerControllerMediaType =“public.image”;     UIImagePickerControllerOriginalImage = UIImage:0x1dd79520“;

现在,如果您获得 UIImagePickerControllerOriginalImage 的价值,那么您可以在此 UIImage 中保存价值。

现在使用它。

UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];

OR

UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

希望这会对你有所帮助。