如何正确保存和读取图像?

时间:2018-12-19 13:59:59

标签: objective-c image path save nsuserdefaults

如何正确保存和读取图像?每次更新应用程序版本后,程序都希望再次保存新图片。

保存图像:

+(void)setImage:(UIImage*)image {

NSData *imageData = UIImageJPEGRepresentation(image, 1);

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *imagePath = [documentsPath stringByAppendingPathComponent:@"image.jpg"];

BOOL writtenToFile = [imageData writeToFile:imagePath atomically:YES];

[[NSUserDefaults standardUserDefaults] setObject:imagePath forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
}

读取图像:

+(UIImage*)getImage {
NSString *imagePath = [[NSUserDefaults standardUserDefaults] objectForKey:key];
if (imagePath) {
    return [UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]];
}

return nil;
}

在UserDefaults中设置对象始终为空。

1 个答案:

答案 0 :(得分:0)

请不要保存用户默认图像的完整路径,因为它包含容器GUID。 更新后,此容器GUID会更改。

- (void)setImage:(UIImage *)image {
    NSData *imageData = UIImageJPEGRepresentation(image, 1);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *imagePath = [documentsPath stringByAppendingPathComponent:@"image.jpg"];

    BOOL writtenToFile = [imageData writeToFile:imagePath atomically:YES];

    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (UIImage *)getImage {
    BOOL imageExists  = [[NSUserDefaults standardUserDefaults] boolForKey:key];
    if (imageExists) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsPath = [paths objectAtIndex:0];
        NSString *imagePath = [documentsPath stringByAppendingPathComponent:@"image.jpg"];

        return [UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]];
    }

    return nil;
}