iOS: сохранение изображения в UIImageView - PullRequest
0 голосов
/ 27 марта 2012

У меня есть приложение, которое позволяет пользователю выбирать изображение из своей камеры и отображать его в UIImageView.Я обычно использую этот метод для сохранения текста в текстовых полях, и я предполагал, что он будет работать и для изображения, но у меня есть некоторые проблемы с ним.Ошибок нет, но изображение просто не сохраняется.

Это соответствующий код, который я использую:

.h:

#define kFilename9        @"PGdata.plist"
...
- (NSString *)dataFilePath;

.m:

- (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                         NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:kFilename9];
}

- (void)applicationDidEnterBackground:(NSNotification *)notification {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObject:image.image];

    [array writeToFile:[self dataFilePath] atomically:YES];
}
- (void)viewDidLoad
{
    ...  

    NSString *filePath = [self dataFilePath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        image.image = [array objectAtIndex:0];
    }

    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidEnterBackground:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:app];

    [super viewDidLoad];

}

Ответы [ 2 ]

3 голосов
/ 27 марта 2012

Сначала необходимо преобразовать UIImage в PNG или JPG, используя UImagePNGRepresentation или UIImageJPEGRepresentation.Эти функции возвращают NSData, который вы затем можете записать в файл.

1 голос
/ 29 августа 2014

Сохранить можно следующим образом。

UIImage * image;//the image you want to save


 NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *docDir=[paths objectAtIndex:0];

    NSFileManager *filemanager=[NSFileManager defaultManager];

    NSData   *  imagedata=UIImageJPEGRepresentation(image,1);
    NSString *savePath= [docDir stringByAppendingPathComponent:@"imageName.jpg"];

    BOOL isdic=NO;
    BOOL isHave=[filemanager fileExistsAtPath:savePath isDirectory:&isdic];
    if (isHave==YES&&isdic==NO) {
        [filemanager removeItemAtPath:savePath error:nil];
    }

   BOOL result= [imagedata writeToFile:savePath atomically:YES];
...