NSFileManager offers a convenient way to write images to and load them from the documents directory.

If you’re frequently doing that in your project, I suggest to wrap up NSFileManager support in three simple methods:


//saving an image

- (void)saveImage:(UIImage*)image:(NSString*)imageName {

NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.

NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it

NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory

NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]]; //add our image to the path

[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)

NSLog(@"image saved");

}

//removing an image

- (void)removeImage:(NSString*)fileName {

NSFileManager *fileManager = [NSFileManager defaultManager];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", fileName]];

[fileManager removeItemAtPath: fullPath error:NULL];

NSLog(@"image removed");

}

//loading an image

- (UIImage*)loadImage:(NSString*)imageName {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];

return [UIImage imageWithContentsOfFile:fullPath];

}

Now, you can easily save an image like:


[self saveImage: myUIImage: @"myUIImageName"];

or load it like:


myUIImage = [self loadImage: @"myUIImageName"];

or remove it like:


[self removeImage: @"myUIImageName"];

61 Responses to “Using NSFileManager to save an image to or load/remove an image from documents directory”

  • jeffrey:

    -hi, can you help me about this problem:

    1.) Use TabBar controller
    2.) Tabs are -> Photos and Settings
    3.) Photos tab should display photo category listing, option to take new photo
    4.) Selecting one of the photo category should display a photo gallery using scrollview to swipe photos to view next photos
    5.) Selecting each of the Photo will display photo details with option to remove photo, email photo and share to Facebook (these last two features can be done later), edit title and description
    6.) Settings should have an option to display photo gallery vertically or horizontally, lock all photos (avoid removal), ON/OFF sound,
    7.) Background music

  • friendlydeveloper:

    Hi Jeffrey,

    thanks for your comment.

    Well, what you’re asking is quite complex. However, let me try to give you a few hints.

    1 & 2) Start off with the TabBar controller project that comes as an XCode template. “File”->”New Project” ->”Tab Bar Application”. You can hit “Build and Run” right away and it will provide you with two different tabs.

    3) In order to display a photo category listing, I recommend learning about UITableViews. Apple offers some nice examples on their website. Simply log into developer.apple.com, navigate to “Sample Code” and look for the “Simple Drill Down” example.
    To take a new photo, you need to check out UIImagePickerController class. Again, you’ll find another sample inside Apple’s demo code section.

    4) If you would like to display one photo at a time, using a UIScrollView is indeed the right choice. However, if you would like to re-create something similar to the view, that displays photos in a way the photos app does, I recommend to modify a UITableView and put images inside rows.

    5) Photo details could be displayed inside a new UIViewController. Again, I’d like you to check out the “Simple Drill Down” example. It shows you how to push a new UIViewController onto the stack of a UINavigationController
    In order to integrate some social networking features into your app, I recommend share kit: http://www.getsharekit.com.

    6) I’d set some boolean values in there and then read back those values inside the other views, when they are active. Then act depending on whether they are set to YES or NO.

    7) There is another nice example on Apple’s website, that will show you how to play music.

    I hope, this information was at least a bit helpful to you. As you can see, your project is a lot more complex than just saving/loading/deleting images (that’s what this blog entry above was about). It depends on how much you already know about XCode and programming in general to determine, how much time you’re gonna have to spend to work this out.

    If you’re completely new to this and don’t know where to begin, a project like that is probably a bit too much. Anyways, if you really want to do it, there is certainly a way to make it happen. It will take you some time though.

    In case my suggestions above don’t really help and you still want to do this, I can recommend our live coding sessions: http://www.codingsessions.com. I think most of the topics you mentioned could be discussed and worked out within 2-3 hours.

    Cheers

  • Alex:

    Hi,

    Great examples, many thanks.

    How would you set up the header file for the saved image please?

    Kind Regards
    Alex

  • friendlydeveloper:

    Hi there,

    glad you enjoyed the examples. Can you please explain, what you mean by “setting up the header file for the saved image”? Thanks.

  • Toubey:

    Yeah, indeed – great examples! I used to save files into the NSTemporaryDirectory, as you can already tell by the folder’s name, the data saved in it was lost from time to time. Hopefully this won’t happen again now.

    I’m also wondering what you mean by “setting up the header file for the saved image”, alex.

  • Sami:

    Great example .. but it doesn’t work with me .. i used the first function to save image from bundle to “photos” directory . the code executed successfully .. but no image saved .. !! what do u think ?

  • friendlydeveloper:

    Hi Sami,

    hope I got you right on this one. The methods I provided allow you to save an image to your application’s documents directory. If you want to save an image to the photo library, my method won’t work. In order to save an image to the photo library, use the following code: UIImageWriteToSavedPhotosAlbum(nameOfUIImage, nil, nil, nil);

    If you want to save an image to the photo library, that you’ve previously saved to your documents directory, try this:
    UIImageWriteToSavedPhotosAlbum([self loadImage:@"imageName"], nil, nil, nil); //this will only work, if the loadImage method is inside the same class.

    Hope, this is helpful.

  • Josh K:

    Hi,

    Great bit of code! Helped a huge amount, however a few things lingering that hopefully you can help me with.

    Any portrait photos that I seem to load, load in sideways which os odd, any ideas?

    Also, is there anyway to tell if there is already an image saved under a certain name?

    Any help appreciated, thanks.

  • Steven:

    Great tutorial!!
    Question: I have a viewController that opens the camera and takes a picture. When the camera dismisses it saves the image to Documents as a PNG and gives it a name (myCoolImage.png).
    Im my secondViewController i am trying to retrieve/load the image but will not work.
    Should i use this line of code in my secondViewController “myUIImage = [self loadImage: @"myUIImageName"];” to load the image? I am trying to get it to load when the viewDidLoad and set the image as the background.
    I am able to copy a image to my project and get the image to show that way but cannot get the image that was saved in documents.

    Any suggestions?

    Thanks alot!

    Steve!

  • neet:

    nice example…sir
    can you please help me how to remove image who selected by scrollView and delete in Documents directory…????

  • Viraj:

    Great help..Keep posting..

Leave a Reply

An App, you might like:
We recommend…
You might also like…
Get Adobe Flash playerPlugin by wpburn.com wordpress themes