2011-12-12 7 views
18

Chcę wyodrębnić obraz przy użyciu ALAssetsLibrary i ALAsset bezpośrednio w postaci obiektu NSData.Używanie ALAssetsLibrary i ALAsset wykup obraz jako NSData

Używając NSURL, wyjmuję obraz w następujący sposób.

Teraz robimy zdjęcie jako UIImage, ale muszę zrobić zdjęcie bezpośrednio jako NSData.

Chciałbym to zrobić, ponieważ (czytałem to) po zrobieniu zdjęcia w UIImage, tracimy wszystkie szczegóły EXIF ​​obrazu.

To jest powód, dla którego chcesz wyodrębnić obraz bezpośrednio jako NSData, zamiast robić to

NSData *webUploadData=UIImageJPEGRepresentation(copyOfOriginalImage, 0.5); 

Ten krok sprawia mi stracić wszystkie dane EXIF.

Proszę o pomoc.

Odpowiedz

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

dziękuję za wspaniałą propozycję. Ale czy istnieje sposób, w jaki mogę skompresować obraz? Przed użyciem jako NSData. –

+0

Jeśli dobrze rozumiem, obraz będzie już skompresowany. Domyślną prezentacją będzie prawdopodobnie jpeg lub png – HeikoG

+2

Mam problem z tą techniką podczas importowania wielu zestawów ALA w tym samym czasie, wydaje się, że bufor zostanie ponownie użyty dla następnego elementu. –

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

jesteś pewien ???? –

+0

To zadziałało dla mnie świetnie. – mreynol

0

Stosując ten kod:

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