使用ALAssetsLibrary和ALAsset取出Image作为NSData

时间:2011-12-12 10:47:24

标签: iphone uiimage nsdata exif uiimagejpegrepresentation

我希望以NSData对象的形式直接使用ALAssetsLibrary和ALAsset提取图像。

使用NSURL我以下列方式取出图像。

NSURL *referenceURL =newURL;
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:referenceURL resultBlock:^(ALAsset *asset)
{
     UIImage  *copyOfOriginalImage = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];
}

现在我们将图像作为UIImage,但我需要将图像直接作为NSData。

我希望这样做因为(我已经读过)一旦你在UIImage中拍摄图像,那么我们就会丢失图像的所有EXIF细节。

这就是我想直接以NSData的形式提取图像的原因,而不是这样做

NSData *webUploadData=UIImageJPEGRepresentation(copyOfOriginalImage, 0.5);

这一步让我失去了所有的EXIF细节。

请帮助。

3 个答案:

答案 0 :(得分:33)

        ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
        [assetLibrary assetForURL:[[self.imagedata objectAtIndex:i] resultBlock:^(ALAsset *asset) 
        {
            ALAssetRepresentation *rep = [asset defaultRepresentation];
            Byte *buffer = (Byte*)malloc(rep.size);
            NSUInteger buffered = [rep getBytes:buffer fromOffset:0.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]);
        }];

答案 1 :(得分:0)

使用此代码:

+ (BOOL)exportDataToURL:(NSString *)filePath error:(NSError **)error andAsset:(ALAsset *)asset
{
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];

    if (!handle)
        return NO;

    static const NSUInteger BufferSize = 1024 * 1024;

    ALAssetRepresentation *rep = [asset defaultRepresentation];
    uint8_t *buffer = calloc(BufferSize, sizeof(*buffer));
    NSUInteger offset = 0, bytesRead = 0;

    do {
        @try {
            bytesRead = [rep getBytes:buffer fromOffset:offset length:BufferSize error:error];
            [handle writeData:[NSData dataWithBytesNoCopy:buffer length:bytesRead freeWhenDone:NO]];
            offset += bytesRead;
        } @catch(NSException *exception) {
            free(buffer);

            return NO;
        }
    } while (bytesRead > 0);

    free(buffer);
    return YES;
}

答案 2 :(得分:-1)

UIImage * selImage = [UIImage imageWithCGImage:[asset thumbnail]];       
NSData *baseImage=UIImagePNGRepresentation(selImage);