简体   繁体   中英

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;
}

Your answer is in the first page of the UIImage Class Reference.

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

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 –

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM