我正在开发我的学校项目,我选择构建一个使用相机的应用程序。我已经设法使用它并将其附加到 UIImageView
中,但是当应用程序被终止时,我很难使该图像永久存在。
我的意思是,我希望图像保留在我杀死应用程序并再次打开它时附加的 View 上,因为在我当前的项目中,当我杀死应用程序时,当我再次打开应用程序时图像也消失了.
这是我的代码:
- (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];
最佳答案
您可以像这样从磁盘保存和检索图像:
保存图像:
- (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];
}
关于Objective-C:应用程序被终止时保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12507406/