Tuesday, May 5, 2009

How to save UIImage to my iPhone or iPod touch

A UIImage can be saved as a JPG or a PNG by using NSData representation. 
First, initialize NSData object by using the function 'UIImagePNGRepresentation' or 'UIImageJPGRepresentation'. Then, write the data through writeToFile method. 

The location where the file will be saved is the Documents directory of your application. 
The document directory can be obtained by 'NSSearchPathForDirectoriesInDomains' method.  

The whole code may look like as follows. 

// Make a UIImage 
UIImage *myImage = [UIImage imageNamed:@"myfilename"] ;

//.... Do what you want ....

// Get the location of the Documents directory

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;

NSString *imagePath = [paths objectAtIndex:0] ;

NSString *filename = @"test.png"

NSString *filepath = [NSString stringWithFormat:@"%@/%@", imagePath, filename] ;


// Save the image 
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(myImage)];
[imageData writeToFile:filepath atomically:YES];


1 comment:

  1. Thank you! This is exactly what I was looking for.

    -Venkat

    ReplyDelete