Save an Image to Camera Roll

Thu, May 7

Saving an image to the camera roll on the iPhone is as close as a method call in the UIKit. However, it takes a few steps to wrap together code to manage error handling and notification that the image has been saved. Let’s see how this works.

Let’s begin with the method description to save an image:

  void UIImageWriteToSavedPhotosAlbum(UIImage *image, 
                  id completionTarget, SEL completionSelector, void *contextInfo);

completionTarget refers to the object in which the completionSelector can be found. In other words, what object has the method that will be called once the file write is complete? contextInfo is a void * that you can use to specify content to be passed to the completionSelector.

Obviously, the image is a required paramater. The other three are only needed if you prefer to be notified asynchronously when the write is complete. Here’s how a call to the above method might look:

  // Image to save
  UIImage *img = [UIImage imageNamed:@"ImageName.png"];  
 
  // Request to save the image to camera roll
  UIImageWriteToSavedPhotosAlbum(img, self, 
              @selector(image:didFinishSavingWithError:contextInfo:), nil);

Here we are specifying that the selector to be called upon completion is within this object (self). A template for this selector could look as follows:

  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error 
             contextInfo:(void *)contextInfo
  {
    // Was there an error?
    if (error != NULL)
    {
      // Show error message...
 
    }
    else  // No errors
    {
      // Show message image successfully saved
    }
  }

Add code for displaying the appropriate message based on success or failure of the image save, and you’re good to go.

6 comments

Is it possible to save the image into a “custom” album as opposed to the generic “Saved Photos” album? and follow-up… is there a way to pull an enumeration of images by album name? Or do I need to re-impl the photo library to get categorized custom images?

thoughts? anything would be appreciated.

by Matt Wyman on Jun 2, 2009. #

hi matt

were u able to find a solution.
I have same scenario where i want to store selected image to a custom location.
do let me know if u find a solution.

by sachin on Jul 24, 2009. #

Nope guys.
You cannot create a new directory.
Sorry.

by Taytus on Oct 13, 2009. #

Using UIImage *img = [UIImage imageNamed:@”image0.jpg”]; How do I add more than one image? This works for my first image but the other 24 will not work? Thanks so much!

Rob.

by rob on Oct 30, 2009. #

thank you for this quick tip ;)

by tomkowz on Dec 8, 2011. #

It helps me a lot, thank u.

by adi on Apr 25, 2012. #