Thursday, 10 November 2011

Camera Application to Take Pictures and Save Images to Photo Album


It’s surprising easy to create a bare bones camera application on the iPhone.UIImagePickerController provides a means to access the camera, take a photo and preview the results. There is also an option to allow resizing and scaling of a photo once captured. UsingUIImageWriteToSavedPhotosAlbum in the UIKit, you can easily save an image to the Photo Album.
The image on the left in the figure below shows the camera active in the application. The image on the right is the preview option once a photo has been taken.
Start the Camera
To work with the camera we begin by creating a UIImagePickerController object and setting the sourceType to UIImagePickerControllerSourceTypeCamera. For this example, I setallowsImageEditing to NO to disable editing of photos image. I use presentModalViewController to initiate the display of the camera.
// Create image picker controller
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
 
// Set source to the camera
imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;
 
// Delegate is self
imagePicker.delegate = self;
 
// Allow editing of image ?
imagePicker.allowsImageEditing = NO;
 
// Show image picker
[self presentModalViewController:imagePicker animated:YES];
Save Image to Photo Album
Once a photo has been taken, the method didFinishPickingMediaWithInfo will be called, providing the opportunity to write the image to the Photo Album:
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
  // Access the uncropped image from info dictionary
  UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
 
  // Save image
  UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
 
  [picker release];
}
Notice the call selector reference above, this selector will be called once the image has been written to the system. For this example I display an alert showing the result of attempting to save the image:
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
  UIAlertView *alert;
 
  // Unable to save the image  
  if (error)
    alert = [[UIAlertView alloc] initWithTitle:@"Error" 
                            message:@"Unable to save image to Photo Album." 
                            delegate:self cancelButtonTitle:@"Ok" 
                            otherButtonTitles:nil];
  else // All is well
    alert = [[UIAlertView alloc] initWithTitle:@"Success" 
                            message:@"Image saved to Photo Album." 
                            delegate:self cancelButtonTitle:@"Ok" 
                            otherButtonTitles:nil];
  [alert show];
  [alert release];
}

No comments:

Post a Comment