Wednesday, June 26, 2013

Store image in Document Directory and Retrieve it in iOS

In this Example i will show how to store image in document directory and Retrieve it.

Following Method we will use to store.

1.NSSearchPathForDirectoriesInDomains : Creates a list of directory search paths. Creates a list of path strings for the specified directories in the specified domains. The list is in the order in which you should search the directories. If expandTilde is YES, tildes are expanded as described in stringByExpandingTildeInPath. You should consider using the NSFileManager methods URLsForDirectory:inDomains: and URLForDirectory:inDomain:appropriateForURL:create:error:. which return URLs, which are the preferred format.

Let Start
here imgData is in NSData Format.

 >>Storing image in document Directory.


NSData *imgData=UIImagePNGRepresentation([UIImage imageNamed:@"Test.png"]);


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            NSString *localFilePath= [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"frame_%d.jpeg",1]];
            NSLog(@"local file path at save --------------- %@",localFilePath);
[imgData writeToFile:localFilePath atomically:YES];

 >> Retrieve Image from document Directory

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath= [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"frame_%d.jpeg",1]];
    


UIImage *givenImage = [UIImage imageWithContentsOfFile:localFilePath];


NSData *myimg =  UIImageJPEGRepresentation(givenImage,0.5);
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
img.image=[UIImage imageWithData:myimg];
[self.view addSubview:img];


            


No comments:

Post a Comment