Objective-C:应用程序被终止时保存图像

标签 objective-c ios uiimageview uiimage uiimagepickercontroller

我正在开发我的学校项目,我选择构建一个使用相机的应用程序。我已经设法使用它并将其附加到 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/

相关文章:

iphone - 在 UIImage 顶部绘制透明圆圈 - iPhone SDK

ios - 记住我使用 UISwitch 和 NSUserDefaults ios 的功能

ios - 如何获得行数?

iphone - 是否可以按国家/地区控制 iPhone 应用程序图标和价格?

ios - 如何根据条件设置初始 View Controller ?

objective-c - 如何为 UIImageView 随机器实现滑动手势

ios - 我可以从 iOS 将 MP3 文件上传到我的服务器吗?

ios - 在 Swift 中的 sendSynchronousRequest 方法中传递子类变量

javascript - 无法在物理 iOS 设备 (9.3) 上启动 react-native

ios - 更改 UIImageView 中的图像,其他 XCode 问题