UIImagePickerController Save to Disk then Load to UIImageView
- by Harley Gagrow
Hi,
I have a UIImagePickerController that saves the image to disk as a png. When I try to load the PNG and set a UIImageView's imageView.image to the file, it is not displaying.
Here is my code:
(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];
}
Then here is how I try to load it:
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"];
}
I get the message that it's trying to load the imageView in the debugger, but the image is never displayed in the imageView. Can anyone tell me what I've got wrong here?
Thanks a bunch.