2012-07-30 38 views
2

我的iPhone應用程序有一個數組用於存儲用戶窗體庫選擇的圖像路徑。 我想使用ALAssetsLibrary將陣列中的所有圖像路徑轉換爲uiimage。 我該怎麼做這個動作?我嘗試使用循環,但不能。 Thx尋求幫助。如何使用ALAssetsLibrary將圖像路徑轉換爲uiimage

ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease]; 
[library assetForURL:[filePath objectAtIndex:0] resultBlock:^(ALAsset *asset) { 
    UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]]; 
    [fileImage addObject:image]; 
} failureBlock:^(NSError *error) { 

}]; 
+0

可以表明,要存儲在陣列中的路徑.. – Leena 2012-07-30 13:16:06

+0

資產庫://asset/asset.JPG ID = 1000000192&EXT = JPG文件路徑(陣列)是存儲用戶選擇的iPhone內置圖庫的圖像路徑。 Thx尋求幫助。 – user1562536 2012-07-31 09:54:32

回答

6

請使用下面的代碼

typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset); 
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);     
               
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset){ 
               
ALAssetRepresentation *rep = [myasset defaultRepresentation]; 
CGImageRef iref = [rep fullResolutionImage]; 
         
if (iref){ 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      UIImage *myImage = [UIImage imageWithCGImage:iref scale:[rep scale] orientation:(UIImageOrientation)[rep orientation]]; 
      [fileImage addObject:myImage]; 
      //binding ur UI elements in main queue for fast execution 
      //self.imageView.image = myImage; 
     }); 

                          
     }       
};       
               
ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror){ 
               
    //failed to get image. 
};             
               
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease]; 
[assetslibrary assetForURL:[filePath objectAtIndex:0] resultBlock:resultblock failureBlock:failureblock]; 

注:確保,你[文件路徑objectAtIndex:0]將是一個NSUrl對象。請將其轉換爲NSUrl,如果不是。

實施例:

ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease]; 

NSURL myAssetUrl = [NSURL URLWithString:[filePath objectAtIndex:0]]; 

assetslibrary assetForURL:myAssetUrl resultBlock:resultblock failureBlock:failureblock]; 
+0

如何使用for循環將filePath(數組)中的所有圖像路徑轉換爲使用ALAssetsLibrary的uiimage。我不熟悉塊。 Thx尋求幫助。在執行「assetslibrary assetForURL:myAssetUrl resultBlock:resultblock failureBlock:failureblock」行之後的 – user1562536 2012-07-31 04:28:19

+0

,結果塊將在另一個線程中被調用。您將在「myImage」對象中獲得相應的url圖像。將該圖像添加到您的數組中。你可以檢查數組的數量,以確定你是否得到所有的圖像(行[「fileImage addObject:myImage];」 – 2012-07-31 07:43:42

+0

當這些代碼運行在iPhone 4.3模擬器,它是成功的獲取圖像,但運行在iPhone 3GS 4.3 .3(真實設備),它沒有得到圖像,它將進入「failureblock」。filePath(陣列)是存儲圖像路徑的iPhone內置圖庫,由用戶選擇。Thx的幫助。 – user1562536 2012-07-31 09:51:48

相關問題