Save and Load UIImage in Documents Directory on iPhone – XCode iOS

The following function saves UIImage in test.png file in the user Document folder:

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)saveImage: (UIImage*)image
{
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: @"test.png"] ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
}

The following function loads UIImage from the test.png file:

1
2
3
4
5
6
7
8
9
10
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: @"test.png"] ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}

[via wmdeveloper]

Namit Gupta

iOS Consultant at @RapidCircle. Passionate about Mobile Apps. Loves to Design. You can reach him on his social profiles below.

Comments 22

    1. Hi Patti, we are not using ImageView anywhere in the above code. You should be doing something wrong. Please share your code here. I’ll have a look at it. Cheers.

  1. Is there a way to modify this code to save/load from the camera roll?

    Also, I would really like to take this sequence of images and turn it into a video. Ive seen several posts and articles on doing this but they are all old posts that do not seem to work any longer.

    Thanks,
    Rich

      1. I want to upload the image from UIImagePickerController directly to my server using mvc.

        Once i click image i place it on my uiimageview but somehow cannot post the image using nsmutablerequest to my server.

        1. Hi, you first need to convert the Image to NSData. And send it as MultipartFormData. Using a third party library such as AFNetworking would be easier.

  2. Hi Namit, I had a question with respect to saving images in documents directory… Every time I rebuild the application and execute I lose the images… Is there any way to handle this. Is it because it is a simulator I have this problem.. and when I execute on a real device have will not be an issue.

    Thanks
    Vijaya

Leave a Reply