我正在开发我的学校项目,我选择构建一个使用相机的应用程序。我已经设法使用它并将其附加到UIImageView
,但是当应用程序被杀时,我很难将该图像永久化。
我的意思是,我希望图像保留在我附加它的视图上,当我杀死应用程序并再次打开它时,因为在我当前的项目中,当我杀死应用程序时,当我再次打开应用程序时图像也消失了
这是我的代码:
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
insertPhoto1.contentMode=UIViewContentModeCenter;
[insertPhoto1 setImage:image];
[self dismissModalViewControllerAnimated:YES];
}
这适用于Tap:
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
}
else
{
[imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
[imagePicker setDelegate:self];
[self presentModalViewController:imagePicker animated:YES];
答案 0 :(得分:1)
您可以像这样从磁盘保存和检索图像:
保存图片:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData* imageData = UIImageJPEGRepresentation(image, 1.0);
NSString* imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/photo1.png"];
[imageData writeToFile:imagePath atomically:YES];
insertPhoto1.contentMode = UIViewContentModeCenter;
[insertPhoto1 setImage:image];
[self dismissModalViewControllerAnimated:YES];
}
在UIViewController viewWillAppear中检索图像:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSString* imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/photo1.png"];
UIImage* imageFromFileSystem = [UIImage imageWithContentsOfFile:imagePath];
UIImageView imageView = [[UIImageView alloc] initWithImage:imageFromFileSystem];
[self.view addSubView:imageView];
}
答案 1 :(得分:0)
一种选择是在应用程序被杀死时将照片保存在NSUserDefaults中。 保存图片:
UIImage* image = [UIImage imageNamed:@"example_image.png"];
NSData* imageData = UIImageJPEGRepresentation(image, 1.0);
NSString* imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/saved_example_image.png"];
[imageData writeToFile:imagePath atomically:YES];
然后,您可以在再次启动应用时调用该图像。 检索图像:
NSString* imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/saved_example_image.png"];
UIImage* imageFromFileSystem = [UIImage imageWithContentsOfFile:imagePath];