Search code examples
iosimagephotosalassetslibraryalasset

How to copy an image file from iOS Photo Library (ALAssetsLibrary) to the local directory of an App?


I can get images from Photo Library through ALAssetsLibrary:

void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop){
        if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
            // Copy the photo image to the `/Documents` directory of this App here

        }
    };

    void (^assetGroupEnumerator )(ALAssetsGroup*, BOOL*) = ^(ALAssetsGroup *group, BOOL *stop){
        if (group != nil) {
            [group enumerateAssetsUsingBlock:assetEnumerator];
        }
    };
    // fetch
    ALAssetsLibrary *library = [ALAssetsLibrary new];
    [library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:assetGroupEnumerator failureBlock:^(NSError *error) {
        NSLog(@"failed");
    }];

I want to copy specific images to the local directory (App_home/Documents), but I don't know how to exactly do this job by handling ALAsset objects.


Solution

  • Try with following Code

    ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
    [assetLibrary assetForURL:YourURL resultBlock:^(ALAsset *asset) 
        {
           ALAssetRepresentation *rep = [asset defaultRepresentation];
           Byte *buffer = (Byte*)malloc(rep.size);
           NSUInteger buffered = [rep getBytes:buffer fromOffset:0 length:rep.size error:nil];
           NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];//this is NSData may be what you want
          [data writeToFile:photoFile atomically:YES];//you can save image later
       }
        failureBlock:^(NSError *err) 
        {
          NSLog(@"Error: %@",[err localizedDescription]);
    
        }
    ];
    

    For get Image In document directory

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *newPath = [documentsDirectory stringByAppendingPathComponent:@"Your_Image_Name"];
    UIImage *myImg = [UIImage imageWithContentsOfFile:newPath]