Is it possible to save images captured by the camera on the iphone to a custom directory or somewhere on the iphone rather than saving to the camera roll?
I would like to save images to the device and then h开发者_JS百科ave access to the at a later stage, rather than reading from the camera roll using ALAssets.
Is this possible?
Yes you can save them to your apps' documents folder. Here is an example:
// Create path
NSString *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/ImageName.png"];
// Write image to PNG
[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
To retrieve it:
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
To list all files in a directory:
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager directoryContentsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];
for (NSString *s in fileList){
NSLog(s);
}
Use this to write
// imageData = NSData object
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *imageCacheDirPath = [docsPath stringByAppendingPathComponent:@"anyFolderName"];
NSString *imageCachePath = [imageCacheDirPath stringByAppendingPathComponent:@"image.jpg"];
[imageData writeToFile:imageCachePath atomically:YES];
And the following snippet to read the data again:
// Get path of image
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *imageCacheDirPath = [docsPath stringByAppendingPathComponent:@"anyFolderName"];
NSString *imageCachePath = [imageCacheDirPath stringByAppendingPathComponent:@"image.jpg"];
NSData *imageData = [NSData dataWithContentsOfFile:imageCachePath];
Note that in this example the image is stored in a subfolder of your "Documents" folder and this folder is called "anyFolderName". The variable docsPath contains the Path to the "Documents" folder of your dir.
Note that this is only the code I use, its from iOS 3.0 times, there might be better ways to store an image to the Documents folder of your app.
精彩评论