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"];

Thx, save me a lot of time.
At line 15, it said missing something, I added “contents” and it works:
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
You’re welcome! Thanks for the correction. That must have accidentally slipped through
Hey, thx for this. May I ask is there anyway to rename an image by using NSFileManager?
Thanks very much!
Hi,
thanks for the feedback!
Well, off the top of my head you could try the following:
1) Get the image you want to rename, using one of the methods above
2) Save this image under the new name
3) Delete the old image = the one you retrieved in (1)
To make it look nice, you could wrap these 3 steps inside one handy method. Maybe something like this:
- (void)renameImage:(NSString*)originalImageName:(NSString*)newImageName {
UIImage *tempImage = [[UIImage alloc] init]; //create a temporary UIImage object
tempImage = [self loadImage:originalImageName]; //load the image you want to rename
[self saveImage:tempImage:newImageName]; //save the image under the new name
[self removeImage:originalImageName]; //delete the old image
[tempImage release]; //release the temporary image
}
Finally, call this method above whenever you want to rename an image:
[self renameImage:@"I_Love_You":@"I_HATE_YOU"];
Please note: Code above is untested. If you run into problems, let me know.
Hi,
Thanks again!
I think I missed something, I want to rename pictures in iphone by using NSFileManager.
I did test the code in Xcode, however the name of pictures in iphone could not be renamed.
Is the code can be applied on iphone app?
No problem
Not sure, if I get you right on this one. You want to rename pictures inside your application bundle or you want to rename pictures inside your iPhone photo library? In case it’s the latter, I’m afraid that’s not possible, since you can only do stuff inside your app’s sandbox environment.
The code I suggested actually takes an image, that has already been saved inside your app’s documents directory and re-saves it under a new name. Then it deletes the old image. In other words, it’s a “complicated”, yet effective way of renaming a picture.
In fact, at first I did want to rename pictures inside my iPhone library, but I knew that’s possible. I also download some softwares to test if I could rename images inside iPhone library, and still not successed.
Therefore, I want to rename them by using NSFileManager.
May I ask, if I want to rename pictures inside my application bundle, can I add the code into a file, then put the file to the Resources folder of my Xcode project?
You can not make any changes to images inside your iPhone photo library. Apple provides UIImagePicker, if you want to get an image from your photo library inside your application. There is also a way to save images to the photo library, but besides that you have no way to access the iPhone’s photo library. This includes renaming images.
However, if the image is inside your app’s documents directory, then you can “rename” an image, using the methods I provided above.
“May I ask, if I want to rename pictures inside my application bundle, can I add the code into a file, then put the file to the Resources folder of my Xcode project?”. Sorry, you need to explain that one. All code, that gets executed at runtime has to be compiled. If you simply write lines of code to a file and put them inside your resources folder, they will never do a thing.
Hope, this information was helpful to you. Feel also welcome to ask for help on http://www.iphonedevsdk.com or http://www.stackoverflow.com
Good luck!
Hi,
Thanks very much!!
Your explaination about can not rename pictures inside my iPhone photo library is very helpful and that helps a lot!
For some reason i can’t get it to work. The console says the image was saved but i look in the camera roll an it’s not there. i made a button to save the image but it’s not saving.
Using my methods, your images are saved to your “documents directory”. The “documents directory” is like a folder, only your app can access. What you want is saving the image(s) directly to your camera roll.
The following line of code will do that:
UIImageWriteToSavedPhotosAlbum(UIImage, nil, nil, nil); //replace UIImage with name of your UIImage or in case you are using a UIImageView: nameOfUIImageView.image
Let me know, if this works for you.
Cheers
Cool that works. Now what if i want to delete an image from the camera roll?
I’m using the UIImageWriteToSavedPhotosAlbum method to save my images. Now I just need to know how to delete them from the camera roll.
Good to hear
Well, I’m pretty sure (99.9999%), that you can’t delete images from your camera roll. You can allow users to save them to your camera roll and pick them, using a UIImagePickerController.
Let me know, if this information is helpful to you.
Cheers
Ok thanks. Very very helpful
hi thanks for the tutorial it is very helpful.But i have a doubt here your saving image at one path even i did same.I also saved image in another path.Here is my problem how can i reload the image from 2nd saved path.
Hi,
thanks for your feedback!
Well, you can only save images to the documents directory of your app. I’m pretty sure it’s impossible to save data anywhere else.
So, what you need to do, is assign a unique name to every image you’re saving. This way you will be able to reload it later without problems.
Let me know, if that does/doesn’t make sense.
thanks for the quick replay!sorry am late.My problems i need to get the images from the server which i need to save on iphone and i need to access them later use.So,to save an image does we need to put that image in resources(here my images are in server so can’t keep them in resources)
Continuation to above question.I need to give more details actually my images are stored in server in a folder i can access them and display but i donno how to save in a directory and the image names will be changing(depends on the analysis).I hope you got my point that is how to store those images and access them .
I cleared one of my doubts that is to save the images no need to keep them in resources.But how to give names in save and reload methods to save that particular image and reload it when it was necessary.Because i donno the names of images exactly as i said they will vary and i will get those images by specifying the path i.e url name.sorry for asking again and again but i need some ones help to remove my all headaches.
Hi there,
no problem. Feel welcome to ask any time.
Well, when you use my method above to save an image, you also have to choose a name for that image. The “real” name of the image you’re downloading does not matter. You can set any name you like.
For example: [self saveImage:myUIImage:@"image1"]; //myUIImage is the name of your UIImage and image1 is the name you’re assigning to this very image when saving.
If you want to reload this image later, simply call: myUIImage = [self loadImage:@"image1];
Please let me know, if this information is helpful to you.
Thanks for the help.Even i did same like you explained..Here am getting the images from server by specifying the path and storing them in a uiimages(some names are given).so as you said i can give that assigned names in myuiimages and some names in place of image1.
Is the problem now solved for you? Please let me know, if you need more help.
yeah problem is solved now.
Hi,
Am new to iphone and have given an app on to develop capturing of image through camera and saving deleting,etc of the image can any on guide me.
Can u send any sample app to :smrafiqsmd@gmail.com
Thank u
Hello,
thanks for checking out my blog and commenting.
Taking an image with your iPhone camera and then saving it is actually a 2 step process. First, you need to learn how to make use of the UIImagePickerController. This will allow you to take an image. Then you can use my NSFileManager sample to actually save this image to your documents directory. I recommend to take a look at this tutorial.
Anyways, being a full time developer, I can not provide custom sample code for free. I hope you understand. However, my company recently started to offer live coding sessions. Within just one hour it should be possible to get a working sample of what you requested. Please feel welcome to get more information here: http://www.codingsessions.com If you have more questions, contact us any time: support.lindmandesign.com
I hope, this information was helpful to you.
Best,
Friendlydeveloper
Hi,
I’m preparing to put my first app onto my iPad and I have studied your file handling routines very carefully. These are the clearest examples I have yet been able to find. I have a couple simple questions.
1. You convert an image to .png before saving. Is this necessary or could it remain .jpg if that was the original file? Or does everything just work better with .png as if that was the native iOS graphic format?
2. You mention that “Documents” is the default directory for an app on the iDevice. Can you create a subdirectory within Documents so that the path might be “Documents/Pictures/MyFace.jpg”? Otherwise, I see no reason to have a pathname when you could simply use a filename. Some apps appear to have rather involved directory structures.
Hi Jim,
thanks for your feedback. Please let me try to help.
1) I think it’s just some habit, I developed over time. I personally prefer .png images, they really give you less trouble
However, if you like, you can also save/load them in .jpeg format. Take a look at UIImageJPEGRepresentation inside the developer documentation.
2) Take a look here: http://stackoverflow.com/questions/1762836/iphone-create-folder-inside-documents-folder
Let me know, if this information was helpful to you.
Cheers
Understood on point #1 about the personal preference for .png files.
#2 at stack overflow makes it all appear to be deliciously simple. I mean,
createDirectoryAtPath
and items like it seem right up my alley!
Now if I could only find a SIMPLE explanation of how to display a pdf page and also to resolve a potential crop box I could finish my app in record time.
For the curious, here’s a proof of concept video:
http://www.youtube.com/jimgramze#p/u/0/MalNDHjnYVU
Thanks again!
Hi Jim,
I believe the easiest way to display a pdf page, is actually to render it inside a UIWebView element. Check out one of my other posts (http://www.friendlydeveloper.com/2010/11/another-iphone-pdf-bug-workaround-coding-ios-development/) and download the sample code I attached to it. Now, although this code covers a different pdf related topic, I use the UIWebView approach to display the document. Give it a try and let me know how it goes
Cheers,
Friendlydeveloper
PS.: Is that you on the other videos playing the piano? I happen to play a bit myself: http://www.youtube.com/watch?v=sCzJ4iP3GtI&feature=related
A couple problems with your project that I have will all of Apple’s sample projects. Firstly, it is set for a different version of the SDK than I have. So I right click on the main project folder and set it to “Latest iOS (currently set to iOS 4.2).” And after taking care of that little problem there is the second problem, which is the build failure, “The identity ‘iPhone Developer’ doesn’t match any valid certificate/private key pair in the default keychain.” This second problem I have no idea what to do with.
Still, I will try to glean from the code what I need and that might take a few days because I’m slow and busy with other things at the moment. PDFs are all the rage with non-paper music whether commercially sold, freeware, or pirated.
My intent is to make my app freeware, allow the user to put his own content on it, and also have in-app purchases where I will lay out music specifically for the iPad having less measures per screen and larger to actually make the whole thing more practical. First I want to get it all working, the store thing will be added later. (I had this evil thought of replacing the red line with a banner ad scanning down and revealing the next page. LOL!!!)
Yes that is me sight reading, pretty bad as it goes on. If it was an actual demo video of the finished product I would have practiced and gone for perfection. Some of my more finished things:
http://www.myspace.com/jim_gramze
You provided quite a production yourself! I absolutely loved the overall feel which is very slick and polished sounding. The drums and “pad” sound just amazing, even awe inspiring. The plucked string instrument sound in the latter half of the piece is too simple and repetitive in the context of the huge backdrop it is playing over. It needs to start simple as it does and get more interesting and complex as it goes on, which it does not.
I use Apple’s Logic Studio, and Make Music’s Finale for scoring purposes. I use a MIDI keyboard to input live playing (Casio PX-130, amazing weighted action feel).
What do you use to produce music? That video was quite good, BTW.
Hi Jim,
thanks for your feedback on my music! Very much appreciated. Well, I use Logic Studio 9.0 combined with some nice Native-Instruments plugins. For input, I use the M-Audio Keystation 88es. Your Casio PX-130 would be a much better choice though
Anyways, about your feedback on the demo code. At the time, I released my demo code, I used the latest version of the SDK (same with Apple sample code). If you open that project later, you have to manually set the latest SDK version yourself. So, your solution is 100% correct.
About the build error. This sounds more complicated, than it actually is. When I compiled it for my iPhone, I had to use my certificate. This of course won’t work on your machine, since you don’t have my certificate. So, what you have to do is this: Inside the project tree (left column), click on the project name (at the very top – blue icon). Now, choose “Project” -> “Edit Project Settings” and inside the new window click on “Build” (if not already selected). Scroll down until you find “Code Signing Identity”. That’s where you have to set your own certificate. Also make sure, that you set your own certificate in “Project” -> “Edit Active Target” (as described above).
In case you can not choose your own certificate, you probably haven’t created one yet. If you do this the very first time, it might be a bit confusing. However, you will find all the details inside the iOS Dev Center on (http://developer.apple.com). Simply navigate to “iOS Provisioning Portal”, once you’re logged in.
Let me know, if this information was helpful to you.
Cheers,
Friendlydeveloper
I’m about to do the whole put your app on your iPad procedure, so yeah, I don’t have the keychain yet. You have been a tremendous help and I don’t know how to thank you. I’ll be in touch when I make significant progress.
Great. Good luck and let me know, if you run into problems…
Hello friendlydeveloper, thx for your tutorial, it is very helpful.
I have some problem to ask for help.
I call the loadImage to load two different image that save as two different name in same file.
Sometime it works normal to return two different image, sometime it return same image or return in wrong order.
The NSLog show the right image file name and path with correct calling order.
Hi Louis,
thanks for commenting on my site. Let me try to help…
I’m not 100% sure, if I get your problem, but let me give it a shot.
By calling the loadImage method, you can only load ONE image at a time. The method returns a UIImage object, which you can then put into a UIImageView object for example.
What are you doing with the loaded image? If you’re using only 1 UIImageView to show it, my guess is, that you immediately replace the first one with the second one or the other way round.
If I didn’t get close to solving your problem, please post some of your code or explain more in detail.
Thanks.
Hi friendlydeveloper,
Thank you for your quick reply.
I’n not use the loadImage Method to get two image at one time.
{
…..
UIImageView *firstView = [[UIImageView alloc] init];
firstView.image = [self loadImage:@"First"];
UIImageView *secondView = [[UIImageView alloc] init];
secondView.image = [self loadImage:@"Secone"];
…..
}
- (UIImage*)loadImage:(NSString*)imageName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *storeHeadFiles = [documentsDirectory stringByAppendingPathComponent:@"/MyImg"];
NSString *fullPath = [storeHeadFiles stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];
UIImage *img = [UIImage imageWithContentsOfFile:fullPath];
NSLog(@” %@ loaded”,fullPath);
return img;
}
This is some of my codes, I call the loadImage method to put the two different image in two UIImageView’s image.
Hello again,
if the image names are correct, I currently don’t see a problem with your code. Did you add your UIImageViews to your UIView, like [self.view addSubview:firstView]; ?
Hi friendlydeveloper,
The image name are correct and UIImageView is add in UIView.
The NSLog is show the right image name Path and method calling Order.
My app have two button use to change views, each of them contain two UIImageView to show two different image.
Actually, the problem will occur while the view, contain loadImage method, was called rapidly. After it start to get the wrong return, it is very easy to get the wrong image.
That is strange. However, I got a feeling, it’s just a minor thinggy. If you like, send your sample project to lindmandesignsupport[at]me.com and I’ll take a look.
It’s grt!!! Thanx!!!
You’re welcome! Thanks for the feedback.
This is really cool. But I am experiencing some issues and do not really know how to resolve it. Basically, I am trying to save an image taken from the iphone camera but do not see the image anywhere. I can see the uiimage in memory and I have put some NSLog statements within the saveImage method and don’t see any errors. I read in another blog to add [fileManager contentsOfDirectoryAtPath:fullPath error:&fileSaveErr] to see the contents of the document directory. This returns a null. I am pretty much stumped at this point. Any ideas on how to troubleshoot this issue?
Thanks for your time
Hi there,
did you add my saveImage method like that:
- (void)imagePickerController:(UIImagePickerController *)currentPicker
didFinishPickingImage:(UIImage*)theImage
editingInfo:(NSDictionary*)editingInfo {
[self saveImage:theImage:@"ImageName"];
[[currentPicker parentViewController] dismissModalViewControllerAnimated:YES];
}
This should correctly save the image to your documents directory and also allow you to call: [self loadImage:@"ImageName]; in order to load it.
If that doesn’t work, there is something wrong with your implementation. If you like, you can send your demo project to lindmandesignsupport[at]me.com and I’ll have a look.
Cheers
Thanks man. very helpful!!
You’re most welcome
HI, I’m quite happy to see that code, but I don’r really understand each line of codes mean!
Could you please take some time to explain me the code because I’m quite new to xcode!
And I also don’t know where to place that code into my projects!
Your prompt reply would be appreciate!
Hello,
thank you very much for your feedback.
I added a few more lines of coding comments to my sample above. I hope, you will find this helpful.
Well, it really depends on your project, where you should put it. However, I believe it’s safe to say, that you can put it into the class, where you want to use it.
Since you are very new to XCode and iOS development, I suggest that check out some of the books available. I can really recommend the iPhone Developer’s Cookbook by Erica Sadun.
In case you are interested in private tutoring, please check out: http://www.codingsessions.com
Good luck!
Cheers,
Friendlydeveloper
I have a coupon app that needs to save an image then load it when the view is left or the app quits. Ive tried using your code to do this but it wont work can you help me?
Hello Peyton,
thanks for your comment! Can you please add a few more details? I’m not quite sure, if I understood your issue 100%. I believe my methods works just fine. I’ve used them in one of my own projects only a couple days ago.
Anyways, if you want to perform tasks when your app quits (= enters background on iOS 4.x), then you need to put code into one of the following methods: – (void)applicationWillResignActive:(UIApplication*)application or – (void)applicationDidEnterBackground:(UIApplication*)application (You can find them inside your AppDelegate)
Unless I’m mistaken, I believe, that it doesn’t make much sense to load any kind of image at that point. Your users simply won’t have time to take a look at the image, since the iPhone will quickly move the app to the background.
Hope, this was helpful and please give me more details, so I can understand your problem a bit better. Thanks