我无法在iOS中保存和检索图像

时间:2015-09-16 11:11:11

标签: ios objective-c uiimage nsdocumentdirectory nsdocumentdirectory-ios8

我无法在iOS中保存和检索图像。我通过这段代码获得了nil图像:

-(NSString *)saveImageDataWithImage:(UIImage *)image
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *photoName = [NSString stringWithFormat:@"%ld.png",
                           (long)[[NSDate date] timeIntervalSince1970]];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:photoName];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:getImagePath])
    {
        NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
        [data1 writeToFile:getImagePath atomically:YES];
    }
    return photoName;
}
-(UIImage *)GetImageFromPath:(NSString *)ImageName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:ImageName];
    UIImage *thumbNail = [[UIImage alloc] initWithContentsOfFile:getImagePath];
    return thumbNail;
}

为什么我会得到零图像?

请帮帮我。

2 个答案:

答案 0 :(得分:2)

-(NSString *)saveImageDataWithImage:(UIImage *)image
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *photoName = [NSString stringWithFormat:@"%ld.png",
                           (long)[[NSDate date] timeIntervalSince1970]];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:photoName];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:getImagePath])
    {
        NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
        [data1 writeToFile:getImagePath atomically:YES];
    }
    return photoName;
}
-(UIImage *)GetImageFromPath:(NSString *)ImageName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:ImageName];
    UIImage *thumbNail = [[UIImage alloc] initWithContentsOfFile:getImagePath];
    return thumbNail;
}

答案 1 :(得分:0)

看起来像目录名中的拼写错误。请将NSDocumentationDirectory替换为NSDocumentationDirectory,它应该有效。