Как показать изображения, хранящиеся в каталоге документов, в галерее iphone?

я делаю скриншот своего представления и сохраняю его в каталоге документов. Но мне нужно отобразить сохраненное изображение в приложении галереи iphone. Я не знаю, как передать изображения в галерею. помогите мне в этом. спасибо в рекламе..

- (IBAction)Screenshot:(id)sender {

    CGSize targetImageSize = CGSizeMake(500, 500);
    // Check for retina image rendering option
    if (NULL != UIGraphicsBeginImageContextWithOptions) UIGraphicsBeginImageContextWithOptions(targetImageSize, NO, 0);
    else UIGraphicsBeginImageContext(targetImageSize);

    CGContextRef context = UIGraphicsGetCurrentContext();
    // The view to be rendered
    [[image layer] renderInContext:context];
    // Get the rendered image
    UIImage *original_image = UIGraphicsGetImageFromCurrentImageContext();
    NSLog(@"%@",original_image);
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/screenshots"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
    //Create folder
//    NSString *documentsDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

   NSString *pngFilePath = [NSString stringWithFormat:@"%@/myPngFile.png",dataPath];
   [UIImagePNGRepresentation(original_image) writeToFile:pngFilePath atomically:YES];
    //[_image1 setImage:original_image];
    UIGraphicsEndImageContext();
}

person muthukumaresh    schedule 23.07.2014    source источник


Ответы (4)


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

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

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

Например :

-(void)savePhoto {
   NSURL *imageURL = receivedURL;
   UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
   UIImageWriteToSavedPhotosAlbum(image, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);
   [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

- (void)   savedPhotoImage:(UIImage *)image
  didFinishSavingWithError:(NSError *)error
           contextInfo:(void *)contextInfo
{
   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                message:@"This image has been saved to your photo album"
                                               delegate:nil
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [alert show];
}
person Abi    schedule 05.11.2014
comment
@muthukumaresh, ты должен принять ответ и сообщить другим, что он работает нормально. - person abi; 17.11.2014

Вы должны сохранить изображение в фотоальбоме, если вам нужно увидеть его в приложении iPhone Photo, используйте этот код

 ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    UIImage *image=//what ever Image you wan tot save and view in photo album of iPhone;

 [library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[SAVEIMAGE imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
        if (error) {
            // TODO: error handling

        } else {




            // TODO: success handling
        }

    }];
person Geet    schedule 23.07.2014

Здесь я передаю строковую переменную в другом представлении так же, как вы можете использовать для изображения. для кода изображения, как показано ниже:

UserDetailsViewController *userDetailsViewController = [[UserDetailsViewController alloc] initWithNibName:@"UserDetailsViewController" bundle:nil];
userDetailsViewController.img = [UIImage imageNamed:@"abc.png"];
[self.navigationController pushViewController:userDetailsViewController animated:YES];
person Anand    schedule 23.07.2014

Используйте приведенный ниже код для сохраненного изображения в галерее

UIImageWriteToSavedPhotosAlbum(imgNewImage, nil, nil, nil);

imgNewImage — это ваш объект UIImage.

person Nirmalsinh    schedule 05.11.2014