0

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

2 回答 2

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];
}
于 2012-09-20T07:01:33.290 回答
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];
于 2012-09-20T07:07:31.247 回答