简体   繁体   English

如何将图像文件从iOS Photo Library(ALAssetsLibrary)复制到App的本地目录?

[英]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: 我可以通过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. 我想将特定图像复制到本地目录( App_home/Documents ),但我不知道如何通过处理ALAsset对象来完成这项工作。

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 用于获取Image In文档目录

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

It may be helpful to you . 它可能对您有所帮助。 In this the outputFileURL is of type NSURL 在这里,outputFileURL的类型为NSURL

   NSData *videoData = [NSData dataWithContentsOfURL:outputFileURL];

  [data writeToFile:destinationPath atomically:YES];//you can save image later

You can get photo raw binary with below implementation and save to your target file. 您可以使用以下实现获取照片原始二进制文件并保存到目标文件。

+ (NSData *)photoAssetRawData:(ALAsset *)photoAsset error:(NSError **)error {
    ALAssetRepresentation *rep = photoAsset.defaultRepresentation;
    NSMutableData *data = [NSMutableData new];
    long long offset = 0;
    uint8_t dataBuffer[PHOTO_READ_CHUNK_SIZE];
    NSError *internalError;
    do {
        NSUInteger readByteLength = [rep getBytes:dataBuffer fromOffset:offset length:sizeof(dataBuffer) error:&internalError];
        if(internalError != nil) {
            if(error != NULL) {
                *error = internalError;
            }
            return nil;
        }
        offset += readByteLength;
        [data appendBytes:(void*)dataBuffer length:readByteLength];
    }
    while (offset < rep.size);
    return data;
}

One thing must be aware, this raw data has not applied any filter iOS default gallery App added, if you want these filter applied, you should get these XMP liked filter from [ALAssetRepresentation metadata] and create filters with [CIFilter filterArrayFromSerializedXMP:inputImageExtent:error:], then apply them on full resolution image, finally save this processed image as JPEG or PNG to file. 有一件事必须要注意,这个原始数据没有应用任何过滤器iOS默认库应用程序添加,如果你想要应用这些过滤器,你应该从[ALAssetRepresentation元数据]获取这些XMP喜欢的过滤器并使用[CIFilter filterArrayFromSerializedXMP:inputImageExtent:error创建过滤器:],然后将它们应用于全分辨率图像,最后将此处理后的图像保存为JPEG或PNG文件。

Below shows how to apply these filters. 下面显示了如何应用这些过滤器。

+ (CGImageRef)applyXMPFilter:(ALAsset *)asset{
    ALAssetRepresentation *rep = [asset defaultRepresentation];
    CGImageRef imageRef = [rep fullResolutionImage];
    NSString *adjustmentXMP;
    NSData *adjustmentXMPData;
    NSError *__autoreleasing error = nil;
    NSArray *filters=nil;
    CGRect extend = CGRectZero;
    //add filter to image
    ALAssetRepresentation *representation = asset.defaultRepresentation;
    adjustmentXMP = [representation.metadata objectForKey:@"AdjustmentXMP"];
    adjustmentXMPData = [adjustmentXMP dataUsingEncoding:NSUTF8StringEncoding];
    extend.size = representation.dimensions;
    filters = [CIFilter filterArrayFromSerializedXMP:adjustmentXMPData inputImageExtent:extend error:&error];
    if(filters)
    {
        CIImage *image = [CIImage imageWithCGImage:imageRef];
        CIContext *context = [CIContext contextWithOptions:nil];
        for (CIFilter *filter in filters)
        {
            [filter setValue:image forKey:kCIInputImageKey];
            image = [filter outputImage];
        }
        imageRef = [context createCGImage:image fromRect:image.extent];
    }
    return imageRef;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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