Friday, 28 March 2014

Save and Load Image From NSDocumentDirectory

//Save Image 

UIImage *image = [[UIImage alloc] initWithData:[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"your Image URL"]];
          
 [Self saveImage:image withImageName:@"ImageName"];

-(void)saveImage:(UIImage*)image withImageName:(NSString*)imageName
{
   
    NSData *imageData = UIImageJPEGRepresentation(image,1.0); //convert image into .jpeg 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:@"%@.jpeg", imageName]]; //add our image to the path
   
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
      
}




//Load Image

[self.imageView setImage:[Self  loadImage:@"ImageName"]];

-(UIImage*)loadImage:(NSString*)imageName
{
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   
    NSString *documentsDirectory = [paths objectAtIndex:0];
   
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpeg", imageName]];
   
    return [UIImage imageWithContentsOfFile:fullPath];
   
}



No comments:

Post a Comment