2014年6月20日 星期五

[iOS] Objective-c save/load image under APP document

Objective-c save/load image under APP document

Save image: 
   [self saveImageInDocumenet:Image withName:@"blue"];

Load image with name: 
   UIImage *image = [self loadImageFromDocumentWithName:@"blue"];


- (void)saveImageInDocumenet:(UIImage *)image withName:(NSString *)name {
    
    if (image != nil) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent:name];

        NSData* data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];

    }
}

- (UIImage*)loadImageFromDocumentWithName:(NSString *)name {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent: name];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    
    return image;
}

沒有留言:

張貼留言