在App - iOS中持久保存图像

时间:2012-10-07 18:59:41

标签: iphone ios image ios6 data-persistence

尝试使用照片选择器选择图像并将该图像保存在apps文件夹内部。

- (void) imagePickerController: (UIImagePickerController *) pickerdidFinishPickingMediaWithInfo: (NSDictionary *) info {

NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToUse;

// Handle a still image picked from a photo album
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
    == kCFCompareEqualTo) {

    editedImage = (UIImage *) [info objectForKey:
                               UIImagePickerControllerEditedImage];
    originalImage = (UIImage *) [info objectForKey:
                                 UIImagePickerControllerOriginalImage];

    if (editedImage) {
        imageToUse = editedImage;
    } else {
        imageToUse = originalImage;
    }
    // Do something with imageToUse

    //save it
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:@"%d", myUniqueID]];
    NSString *imagePath = [imageName stringByAppendingPathComponent:@".png"];

    NSData *webData = UIImagePNGRepresentation(editedImage);
    NSError* error = nil;
    bool success = [webData writeToFile:imagePath options:NULL error:&error];
    if (success) {
        // successfull save
        imageCount++;
        [[NSUserDefaults standardUserDefaults] setInteger:imageCount forKey:@"imageCount"];
        NSLog(@"@Success save to: %@", imagePath);
    }
    else if (error) {
        NSLog(@"Error:%@", error.localizedDescription);
    }
}
...
}

我无法弄清楚writeToFile:::会返回falseerror中没有返回任何值,所以我无法弄清楚什么是错误的。非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

你错过了一个“/”。这一行:

NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:@"%d", myUniqueID]];

应该是:

NSString *imageName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", myUniqueID]];

这句话说:

NSString *imagePath = [imageName stringByAppendingPathComponent:@".png"];

应该是:

NSString *imagePath = [imageName stringByAppendingPathExtension:@"png"];

<强>更新

并且,不应该:

NSData *webData = UIImagePNGRepresentation(editedImage);

如下?

NSData *webData = UIImagePNGRepresentation(imageToUse);