UIImagePickerController - сохранить и загрузить изображение? - PullRequest
1 голос
/ 20 октября 2011

По этой теме, похоже, разбросана информация, но она кажется довольно запутанной, поэтому я не против, чтобы я спросил.

У меня работает UIImagePickerController, позволяя мне сделать фотографию или выбрать из библиотеки, а затем установить UIImageView по своему выбору, чтобы показать, что изображение снято / выбрано.

Однако, как я могу сначала сохранить изображение, а затем загрузить его обратно при повторном открытии приложения? Кроме того, я буду сохранять несколько изображений, поэтому они должны быть однозначно идентифицированы.

Любая помощь будет высоко оценена, спасибо.

1 Ответ

3 голосов
/ 20 октября 2011

Я не знаю, как получить фотографию из фотоальбома во второй раз. Кажется, нет способа восстановить его снова. Мы делаем несколько вещей, чтобы сохранить изображение внутри.

Мы либо конвертируем изображение в NSData и сохраняем его в CoreData, либо сохраняем его в нашей песочнице.

Вот фрагмент кода, который мы используем, это делает одну из нескольких вещей, я получаю изображение из ScreenShot, хотя оно то же самое, когда у вас есть UIImage.

    // go get our screenshot
UIImage* screenShot = [self createScreenShotThumbnailWithWidth:200];
    // Save screen shot as a png in the documents directory with the UUID of the IoCDScreen
    // Saving to Sandbox
     [self saveImage:screenShot withName:currentScreen.itemUUID];

    // save image to Photo Album - though you can't get a ref back to it
    UIImageWriteToSavedPhotosAlbum(screenShot, self, nil, nil);

    //convert our screen shot PNG to NSData and store it in a CoreData Managed Object
currentScreen.screenImageDevelopment =  [NSData dataWithData: UIImagePNGRepresentation( screenShot )];

Вспомогательные функции, используемые выше

    //--------------------------------------------------------------------------------------------------------
    //    saveImage:withName:
    //    Description: Save the Image with the name to the Documents folder
    //
    //--------------------------------------------------------------------------------------------------------

- (void)saveImage:(UIImage *)image withName:(NSString *)name {

        //grab the data from our image
    NSData *data = UIImageJPEGRepresentation(image, 1.0);

        //get a path to the documents Directory
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,  YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

        // Add out name to the end of the path with .PNG
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", name]];

        //Save the file, over write existing if exists. 
    [fileManager createFileAtPath:fullPath contents:data attributes:nil];

}

    //--------------------------------------------------------------------------------------------------------
    //    createScreenShotThumbnailWithWidth
    //    Description: Grab a screen shot and then scale it to the width supplied
    //
    //--------------------------------------------------------------------------------------------------------

-(UIImage *) createScreenShotThumbnailWithWidth:(CGFloat)width{
        // Size of our View
    CGSize size = self.view.bounds.size;

        //First Grab our Screen Shot at Full Resolution
    UIGraphicsBeginImageContext(size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();


        //Calculate the scal ratio of the image with the width supplied.
    CGFloat ratio = 0;
    if (size.width > size.height) {
        ratio = width / size.width;
    } else {
        ratio = width / size.height;
    }

        //Setup our rect to draw the Screen shot into 
    CGRect rect = CGRectMake(0.0, 0.0, ratio * size.width, ratio * size.height);

        //Scale the screenshot and save it back into itself
    UIGraphicsBeginImageContext(rect.size);
    [screenShot drawInRect:rect];
    screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

        //Send back our screen shot
    return screenShot;

}
...