我有一个 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];
}
然后这是我尝试加载它的方法:
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"];
}
我收到消息,它正在尝试在调试器中加载 imageView,但图像从未显示在 imageView 中。谁能告诉我我这里出了什么问题吗?
非常感谢。
您正在写出一个 NSData 对象,而不是图像。您需要读回 NSData 对象并转换为 UIImage。
假设其他一切都正确,请尝试以下操作:
NSData *data = [[NSData alloc] initWithContentsOfFile:[self.managedObject valueForKey:@"imageLocation"]];
UIImage *image = [[UIImage alloc] initWithData:data];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)