Как сохранить картинку в фотобиблиотеку iPhone? - PullRequest
190 голосов
/ 07 октября 2008

Что мне нужно сделать, чтобы сохранить изображение, сгенерированное моей программой (возможно, с камеры, возможно, нет), в системную библиотеку фотографий на iPhone?

Ответы [ 14 ]

409 голосов
/ 07 октября 2008

Вы можете использовать эту функцию:

UIImageWriteToSavedPhotosAlbum(UIImage *image, 
                               id completionTarget, 
                               SEL completionSelector, 
                               void *contextInfo);

Вам нужно только завершение-цель , завершение-выборка и contextInfo , если вы хотите получать уведомления о завершении сохранения UIImage, в противном случае вы можете передать nil.

См. официальную документацию для UIImageWriteToSavedPhotosAlbum().

63 голосов
/ 21 сентября 2010

Устаревший в iOS 9.0.

Существует гораздо более быстрый способ, чем UIImageWriteToSavedPhotos. Альбомный способ сделать это с помощью iOS 4.0+ AssetsLibrary Framework

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    [library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
    if (error) {
    // TODO: error handling
    } else {
    // TODO: success handling
    }
}];
[library release];
27 голосов
/ 24 декабря 2013

Самый простой способ:

UIImageWriteToSavedPhotosAlbum(myUIImage, nil, nil, nil);

Для Swift вы можете обратиться к Сохранение в библиотеку фотографий iOS с помощью swift

13 голосов
/ 02 апреля 2013

Помните одну вещь: если вы используете обратный вызов, убедитесь, что ваш селектор соответствует следующей форме:

- (void) image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo;

В противном случае произойдет сбой с ошибкой, такой как:

[NSInvocation setArgument:atIndex:]: index (2) out of bounds [-1, 1]

10 голосов
/ 30 марта 2010

Просто передайте изображения из массива ему, как показано ниже

-(void) saveMePlease {

//Loop through the array here
for (int i=0:i<[arrayOfPhotos count]:i++){
         NSString *file = [arrayOfPhotos objectAtIndex:i];
         NSString *path = [get the path of the image like you would in DOCS FOLDER or whatever];
         NSString *imagePath = [path stringByAppendingString:file];
         UIImage *image = [[[UIImage alloc] initWithContentsOfFile:imagePath]autorelease];

         //Now it will do this for each photo in the array
         UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        }
}

Извините за опечатку, вроде как сделал это на лету, но вы получите точку

4 голосов
/ 06 октября 2015

Будет работать функция ниже. Вы можете скопировать отсюда и вставить туда ...

-(void)savePhotoToAlbum:(UIImage*)imageToSave {

    CGImageRef imageRef = imageToSave.CGImage;
    NSDictionary *metadata = [NSDictionary new]; // you can add
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    [library writeImageToSavedPhotosAlbum:imageRef metadata:metadata completionBlock:^(NSURL *assetURL,NSError *error){
        if(error) {
            NSLog(@"Image save eror");
        }
    }];
}
4 голосов
/ 19 марта 2015

In Swift :

    // Save it to the camera roll / saved photo album
    // UIImageWriteToSavedPhotosAlbum(self.myUIImageView.image, nil, nil, nil) or 
    UIImageWriteToSavedPhotosAlbum(self.myUIImageView.image, self, "image:didFinishSavingWithError:contextInfo:", nil)

    func image(image: UIImage!, didFinishSavingWithError error: NSError!, contextInfo: AnyObject!) {
            if (error != nil) {
                // Something wrong happened.
            } else {
                // Everything is alright.
            }
    }
4 голосов
/ 14 августа 2013

При сохранении массива фотографий, не используйте цикл for, сделайте следующее

-(void)saveToAlbum{
   [self performSelectorInBackground:@selector(startSavingToAlbum) withObject:nil];
}
-(void)startSavingToAlbum{
   currentSavingIndex = 0;
   UIImage* img = arrayOfPhoto[currentSavingIndex];//get your image
   UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{ //can also handle error message as well
   currentSavingIndex ++;
   if (currentSavingIndex >= arrayOfPhoto.count) {
       return; //notify the user it's done.
   }
   else
   {
       UIImage* img = arrayOfPhoto[currentSavingIndex];
       UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
   }
}
2 голосов
/ 11 марта 2011
homeDirectoryPath = NSHomeDirectory();
unexpandedPath = [homeDirectoryPath stringByAppendingString:@"/Pictures/"];

folderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];

unexpandedImagePath = [folderPath stringByAppendingString:@"/image.png"];

imagePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];

if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:folderPath attributes:nil];
}
1 голос
/ 24 апреля 2016

В Swift 2.2

UIImageWriteToSavedPhotosAlbum(image: UIImage, _ completionTarget: AnyObject?, _ completionSelector: Selector, _ contextInfo: UnsafeMutablePointer<Void>)

Если вы не хотите получать уведомление о завершении сохранения изображения, вы можете передать nil в параметрах completeTarget , завершение-выбора и contextInfo . 1012 *

Пример:

UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.imageSaved(_:didFinishSavingWithError:contextInfo:)), nil)

func imageSaved(image: UIImage!, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
        if (error != nil) {
            // Something wrong happened.
        } else {
            // Everything is alright.
        }
    }

Здесь важно отметить, что ваш метод, который наблюдает за сохранением изображения, должен иметь эти 3 параметра, иначе вы столкнетесь с ошибками NSInvocation.

Надеюсь, это поможет.

...