将图像保存到Documents目录,而不是将其加载到UIImageView中

时间:2015-07-29 11:52:03

标签: ios uiimageview uiimage save load

我一直试图解决这个问题。我有一个应用程序,用户选择一个图像,而不是选定的图像保存到磁盘,然后加载到UIImageView,但无论我尝试什么,这都不起作用。我做了一个小应用程序只是为了测试它,它也不起作用。 imageView保持空白。这是我的代码:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)button:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.allowsEditing = NO;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];

}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
    [self saveImage:selectedImage];
    self.imageView.image = [self loadImage];
    [picker dismissViewControllerAnimated:YES completion:NULL];

}

- (void)saveImage: (UIImage*)image
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:
                      @"image.png" ];
    NSData* data = UIImagePNGRepresentation(image);
    [data writeToFile:path atomically:YES];
}


- (UIImage*)loadImage
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:
                      @"image.png" ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    return image;
}

@end

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您只需要添加UIImagePickerController的委托,以便以下代码解决您的问题。

- (IBAction)button:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.allowsEditing = NO;
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];
}

现在,在.h文件中使用以下代码。

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(nonatomic,weak)IBOutlet UIImageView *imageView;

@end