2011-12-12 17 views
18

Deseo extraer la imagen utilizando ALAssetsLibrary y ALAsset directamente en forma de un objeto NSData.Utilizando ALAssetsLibrary y ALAsset take Image como NSData

Uso de un NSURL Saco la imagen de la siguiente manera.

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

Ahora aquí tomamos la imagen como un UIImage, pero necesito tomar la imagen directamente como NSData.

Deseo hacer esto porque (he leído eso) una vez que tomas la imagen en UIImage, entonces perdemos todos los detalles EXIF ​​de la Imagen.

Esa es la razón por la que desea extraer la imagen directamente como NSData, en lugar de hacer esto

NSData *webUploadData=UIImageJPEGRepresentation(copyOfOriginalImage, 0.5); 

Este paso me hace perder todos los datos EXIF.

Por favor ayuda.

Respuesta

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

Gracias por su maravillosa sugerencia. Pero, ¿hay alguna manera de comprimir la imagen? Antes de usarlo como NSData. –

+0

Si entiendo bien, la imagen ya estará comprimida. La presentación por defecto probablemente sea un jpeg o png – HeikoG

+2

tengo un problema con esta técnica al importar múltiples ALAssets al mismo tiempo, parece como si el buffer se reutilizara para el próximo artículo. –

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

¿estás seguro ??? –

+0

Esto funcionó muy bien para mí. – mreynol

0

Utilizando este código:

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