Saturday, May 21, 2011

Store Images in local database in iPhone SDK

Hello friends,

Generally, we store images for the application in database using blob in sqlite. But this is not efficient method for storing images. When we store image using blob in sqlite, it basically store in binary data. This takes longer time for loading and storing images. When we have to deal with large and large number of images in application then we should go for the following technique.

Following method stores images in local database:

Formally we write database methods in AppDelegate implementation file. Add the following code in your application file.

-(int)StoreImageLocally:(NSString *)FileName1 :(UIImage *)Image
{
//UIImage *IM;
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: FileName1];
[UIImagePNGRepresentation(Image) writeToFile: filePath atomically:YES];
return 0;
}

Above function will be called by following way to call this function in App Delegate class. Above function store image in iPhone's local database with png format.

[self StoreImageLocally:imageName:Image];

Now to retrieve image from local database, use the following method.
-(UIImage *)GetImage:(NSString *)FileName1
{
if(!IM)
[IM release];
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: FileName1];
IM=[[UIImage alloc] initWithContentsOfFile:filePath];
return IM;
}


To use the above function call with following method.

UIImage*  imgphoto=[self GetImage:imageName];

Enjoy..:-)

No comments:

Post a Comment