UIImagePickerController保存到磁盘然后加载到UIImageView

Har*_*row 2 iphone uiimageview uiimagepickercontroller

我有一个UIImagePickerController,它将图像作为png保存到磁盘.当我尝试加载PNG并将UIImageView设置imageView.image为该文件时,它不会显示.

这是我的代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImagePNGRepresentation(image);

    // Create a file name for the image
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    NSString *imageName = [NSString stringWithFormat:@"photo-%@.png",
                           [dateFormatter stringFromDate:[NSDate date]]];
    [dateFormatter release];

    // Find the path to the documents directory
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // Now we get the full path to the file
    NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];

    // Write out the data.
    [imageData writeToFile:fullPathToFile atomically:NO];

    // Set the managedObject's imageLocation attribute and save the managed object context
    [self.managedObject setValue:fullPathToFile forKey:@"imageLocation"];
    NSError *error = nil;
    [[self.managedObject managedObjectContext] save:&error];


    [self dismissModalViewControllerAnimated:YES];
}
Run Code Online (Sandbox Code Playgroud)

那么这是我尝试加载它的方式:

self.imageView.backgroundColor = [UIColor lightGrayColor];
self.imageView.frame = CGRectMake(10, 10, 72, 72);
if ([self.managedObject valueForKey:@"imageLocation"] != nil) {
    NSLog(@"Trying to load the imageView with: %@", [self.managedObject valueForKey:@"imageLocation"]);
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:[self.managedObject valueForKey:@"imageLocation"]];
    self.imageView.image = image;

} else {
    self.imageView.image = [UIImage imageNamed:@"no_picture_taken.png"];
}
Run Code Online (Sandbox Code Playgroud)

我得到的消息是它试图在调试器中加载imageView,但图像永远不会显示在imageView中.谁能告诉我这里有什么问题?

谢谢一堆.

Jor*_*dan 7

你正在写出一个NSData对象,而不是一个图像.您需要重新读取NSData对象并转换为UIImage.

假设其他一切都正确,试试这个:

NSData *data = [[NSData alloc] initWithContentsOfFile:[self.managedObject valueForKey:@"imageLocation"]];
UIImage *image = [[UIImage alloc] initWithData:data];
Run Code Online (Sandbox Code Playgroud)