Search code examples
iphonexcodeiosphoto-gallery

Saving JPG image from Documents to Photo Album - Sample Code


I have generated JPG image, saved to Documents folder, that not comes with bundle. Please help with the building class for saving it to Gallery.

Finnaly with help of kviksilver

To make complete solution:

// tools.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface tools : NSObject {

}

@end

// tools.m

#import "tools.m"

@implementation tools

-(IBAction)saveImage{

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *imagePath=[documentsDirectory stringByAppendingPathComponent:@"file7.jpg"];
    UIImage *image=[UIImage imageWithContentsOfFile:imagePath];
    UIImageWriteToSavedPhotosAlbum(image, self,@selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);
}
@end

In the end have to call it from CPP wrapper:

void onCPPSaveImgToCamRoll ( )
{
    return saveImage;
}

Solution

  • try getting imagePath like this:

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *imagePath=[documentsDirectory stringByAppendingPathComponent:@"Image.jpg"];
    

    then setting image:

     UIImage *image=[UIImage imageWithContentsOfFile:imagePath];
    UIImageWriteToSavedPhotosAlbum(image, self,@selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);
    

    savedPhotoImage:didFinishSavingWithError:contextInfo: will be called when finished saving or failing

    just create two methods in your class:

    -(void)saveImage{ 
    
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    
    NSString *documentsDirectory=[paths objectAtIndex:0]; 
    
    NSString *imagePath=[documentsDirectory stringByAppendingPathComponent:@"Image.jpg"]; 
    
    UIImage *image=[UIImage imageWithContentsOfFile:imagePath]; 
    
    UIImageWriteToSavedPhotosAlbum(image, self,@selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);
    
    
    } 
    - (void)savedPhotoImage:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{ 
    
    // possible error handling
    
    }
    

    and you should be ok –