18

我希望直接以 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 细节。

请帮忙。

4

3 回答 3

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]);
        }];
于 2011-12-12T11:55:42.780 回答
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;
}
于 2014-07-10T02:46:19.363 回答
-1
UIImage * selImage = [UIImage imageWithCGImage:[asset thumbnail]];       
NSData *baseImage=UIImagePNGRepresentation(selImage);
于 2012-11-02T07:11:59.530 回答