如何在Xcode 5 for iOS中保存和加载图像?

时间:2014-09-06 15:35:46

标签: ios image save

我为iPhone制作了一款Flappy Bird风格的应用程序。这个应用程序是这样的,我可以学习应用程序制作背后的编程,并希望很快制作一个更原始和高级的应用程序。

该应用可以加载从您的照片库或iPhone相机拍摄的照片。我用了这段代码:

- (IBAction)didTapPhoto:(UITapGestureRecognizer *)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Take a Photo", @"Use Photo Library", nil];

    [actionSheet showInView:self.view];
}

-(void) pickPhotoFromLibrary {
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self.navigationController presentViewController:self.imagePicker animated:YES completion:nil];
}

-(void) takePhotoWithCamera {
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

    [self.navigationController presentViewController:self.imagePicker animated:YES completion:nil];
}

-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == actionSheet.cancelButtonIndex)return;

    switch (buttonIndex) {
        case 0:
            [self takePhotoWithCamera];
            break;
        case 1:
            [self pickPhotoFromLibrary];
        default:
            break;
    }
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];

    UIImage *image = info[UIImagePickerControllerOriginalImage];

    self.imageView.image = image;
}

问题是:如何保存在ImageView中加载的图片,然后将其加载到另一个ViewController中?

我希望用户拍照,然后将自己用作飞扬的小鸟。我已经制作了Flappy Bird课程,习惯了不同的飞鸟。

唯一的问题是我希望可以将用户选择的图片保存为.png文件,就像保存在支持文件中一样。图片可以保存为默认值,例如@" image1",在另一个ViewController中,您可以设置ImageView加载@" image1"。

1 个答案:

答案 0 :(得分:0)

将图像保存到iPhone本地文件:

NSString *imagePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *imageName = [imagePath stringByAppendingPathComponent:@"MainImage.jpg"];
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 1.0);
BOOL result = [imageData writeToFile:imageName atomically:YES];
NSLog(@"Saved to %@? %@", imageName, (result? @"YES": @"NO"));

加载保存的图像:

NSString *imagePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *imageName = [imagePath stringByAppendingPathComponent:@"MainImage.jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:imageName];