How to select a UIImage from the camera roll (and use it)

- by

The UIImagePickerController can help us do this with ease.

In this example we’ll instantiate it, then we tell it what kind of image we want returned (we’re using an edited version here, but we could just as well return the original, or start using a camera). Next we present a modal view controller where the actual image selection takes place:

    // let's grab a picture from the media library
    UIImagePickerController *myPicker = [[UIImagePickerController alloc]init];
    myPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    myPicker.allowsEditing = YES;
    myPicker.delegate = self;
    // now we present the picker
    [self presentModalViewController:myPicker animated:YES];

For this to work you need to conform to the UIImagePickerControllerDelegate protocol, as well as the UINavigationControllerDelegate (the latter does not need any methods – it’s just so that the warning to myPicker.delegate = self goes away really).

The two methods we need from the first protocol are to deal with a selection and a cancellation. In this example I’m displaying the returned image in a UIImageView:

// an image is selected
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    [self dismissModalViewControllerAnimated:YES];
    UIImage *chosenImage = [info objectForKey:UIImagePickerControllerEditedImage];
    self.myPicture.image = chosenImage;

// user hits cancel
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
    [self dismissModalViewControllerAnimated:YES];

If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.