2011-12-12 7 views
18

ALAssetsLibraryとALAssetをNSDataオブジェクトの形式で直接使用してイメージを抽出します。ALAssetsLibraryとALAssetを使用してNSDataとしてイメージを取り出します

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 *webUploadData=UIImageJPEGRepresentation(copyOfOriginalImage, 0.5); 

この手順を行うので、私は直接のNSDataとして画像を抽出したい理由です

は私がすべてのEXIFの詳細を失うことになります。

お願いします。このコードの使用

答えて

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

をあなたの素晴らしい提案をいただき、ありがとうございます。 しかし、画像を圧縮する方法はありますか? NSDataとして使用する前に。 –

+0

私が正しく理解すれば、イメージはすでに圧縮されています。デフォルトのプレゼンテーションはおそらくJPEGまたはPNGになります – HeikoG

+2

同じテクニックで複数のALAssetsをインポートする際にこのテクニックに問題があります。バッファが次のアイテムに再利用されたようです。 –

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

あなたは本当ですか? –

+0

これは私にとって素晴らしい仕事でした。 – mreynol

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