iOS開發之獲取系統相冊中的圖片與視頻(內帶url轉換)

@話不多說,直接上代碼

[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. #import <AssetsLibrary/AssetsLibrary.h>  // 必須導入  
  2.   
  3. // 照片原圖路徑  
  4. #define KOriginalPhotoImagePath   \  
  5. [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"OriginalPhotoImages"]  
  6.   
  7. // 視頻URL路徑  
  8. #define KVideoUrlPath   \  
  9. [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"VideoURL"]  
  10.   
  11. // caches路徑  
  12. #define KCachesPath   \  
  13. [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]  
  14.   
  15. // MainViewController  
  16. @interface MTHMainViewController ()  
  17.   
  18. @property (nonatomic,strongMTHNextViewController *nextVC;  
  19. @property (nonatomic,strong) NSMutableArray        *groupArrays;  
  20. @property (nonatomic,strong) UIImageView           *litimgView;  
  21.   
  22. @end  
  23.   
  24. @implementation MTHMainViewController  
  25.   
  26. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  27. {  
  28.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  29.     if (self) {  
  30.         // Custom initialization  
  31.     }  
  32.     return self;  
  33. }  
  34.   
  35. - (void)viewDidLoad  
  36. {  
  37.     [super viewDidLoad];  
  38.     // Do any additional setup after loading the view.  
  39.     self.navigationItem.title = @"Demo";  
  40.     self.view.backgroundColor = [UIColor clearColor];  
  41.       
  42.     // 初始化  
  43.     self.groupArrays = [NSMutableArray array];  
  44.       
  45.     // 測試BarItem  
  46.     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"測試" style:UIBarButtonItemStylePlain target:self action:@selector(testRun)];  
  47.       
  48.     // 測試手勢  
  49.     UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didClickPanGestureRecognizer:)];  
  50.     [self.navigationController.view addGestureRecognizer:panRecognizer];  
  51.       
  52.     // 圖片或者視頻的縮略圖顯示  
  53.     self.litimgView = [[UIImageView alloc] initWithFrame:CGRectMake(100200120120)];  
  54.     [self.view addSubview:_litimgView];  
  55. }  
  56.   
  57.   
  58. - (void)testRun  
  59. {  
  60.     __weak MTHMainViewController *weakSelf = self;  
  61.     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
  62.         ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOLBOOL *stop) {  
  63.             if (group != nil) {  
  64.                 [weakSelf.groupArrays addObject:group];  
  65.             } else {  
  66.                 [weakSelf.groupArrays enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOLBOOL *stop) {  
  67.                     [obj enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOLBOOL *stop) {  
  68.                         if ([result thumbnail] != nil) {  
  69.                             // 照片  
  70.                             if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]){  
  71.                                   
  72.                                 NSDate *date= [result valueForProperty:ALAssetPropertyDate];  
  73.                                 UIImage *image = [UIImage imageWithCGImage:[result thumbnail]];  
  74.                                 NSString *fileName = [[result defaultRepresentation] filename];  
  75.                                 NSURL *url = [[result defaultRepresentation] url];  
  76.                                 int64_t fileSize = [[result defaultRepresentation] size];  
  77.                                   
  78.                                 NSLog(@"date = %@",date);  
  79.                                 NSLog(@"fileName = %@",fileName);  
  80.                                 NSLog(@"url = %@",url);  
  81.                                 NSLog(@"fileSize = %lld",fileSize);  
  82.                                   
  83.                                 // UI的更新記得放在主線程,要不然等子線程排隊過來都不知道什麼年代了,會很慢的  
  84.                                 dispatch_async(dispatch_get_main_queue(), ^{  
  85.                                     self.litimgView.image = image;  
  86.                                 });  
  87.                             }  
  88.                             // 視頻  
  89.                             else if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo] ){  
  90.                               
  91.                                 // 和圖片方法類似  
  92.                             }  
  93.                         }  
  94.                     }];  
  95.                 }];  
  96.   
  97.             }  
  98.         };  
  99.           
  100.         ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error)  
  101.         {  
  102.               
  103.             NSString *errorMessage = nil;  
  104.               
  105.             switch ([error code]) {  
  106.                 case ALAssetsLibraryAccessUserDeniedError:  
  107.                 case ALAssetsLibraryAccessGloballyDeniedError:  
  108.                     errorMessage = @"用戶拒絕訪問相冊,請在<隱私>中開啓";  
  109.                     break;  
  110.                       
  111.                 default:  
  112.                     errorMessage = @"Reason unknown.";  
  113.                     break;  
  114.             }  
  115.               
  116.             dispatch_async(dispatch_get_main_queue(), ^{  
  117.                 UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"錯誤,無法訪問!"  
  118.                                                                    message:errorMessage  
  119.                                                                   delegate:self  
  120.                                                          cancelButtonTitle:@"確定"  
  121.                                                          otherButtonTitles:nil, nil nil];  
  122.                 [alertView show];  
  123.             });  
  124.         };  
  125.           
  126.           
  127.         ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc init];  
  128.         [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll  
  129.                                      usingBlock:listGroupBlock failureBlock:failureBlock];  
  130.     });  
  131. }  

      @但是:

      按照上面方法直接取出來的路徑是無法傳輸的,必須自己轉化成NSData對象重新寫入沙盒路徑

[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. // 將原始圖片的URL轉化爲NSData數據,寫入沙盒  
  2. - (void)imageWithUrl:(NSURL *)url withFileName:(NSString *)fileName  
  3. {  
  4.     // 進這個方法的時候也應該加判斷,如果已經轉化了的就不要調用這個方法了  
  5.     // 如何判斷已經轉化了,通過是否存在文件路徑  
  6.     ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];  
  7.     // 創建存放原始圖的文件夾--->OriginalPhotoImages  
  8.     NSFileManager * fileManager = [NSFileManager defaultManager];  
  9.     if (![fileManager fileExistsAtPath:KOriginalPhotoImagePath]) {  
  10.         [fileManager createDirectoryAtPath:KOriginalPhotoImagePath withIntermediateDirectories:YES attributes:nil error:nil];  
  11.     }  
  12.     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
  13.         if (url) {  
  14.             // 主要方法  
  15.             [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {  
  16.                 ALAssetRepresentation *rep = [asset defaultRepresentation];  
  17.                 Byte *buffer = (Byte*)malloc((unsigned long)rep.size);  
  18.                 NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:((unsigned long)rep.size) error:nil];  
  19.                 NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];  
  20.                 NSString * imagePath = [KOriginalPhotoImagePath stringByAppendingPathComponent:fileName];  
  21.                 [data writeToFile:imagePath atomically:YES];  
  22.             } failureBlock:nil];  
  23.         }  
  24.     });  
  25. }  
  26.   
  27. // 將原始視頻的URL轉化爲NSData數據,寫入沙盒  
  28. - (void)videoWithUrl:(NSURL *)url withFileName:(NSString *)fileName  
  29. {  
  30.     // 解析一下,爲什麼視頻不像圖片一樣一次性開闢本身大小的內存寫入?  
  31.     // 想想,如果1個視頻有1G多,難道直接開闢1G多的空間大小來寫?  
  32.     ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];  
  33.     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
  34.         if (url) {  
  35.             [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {  
  36.                 ALAssetRepresentation *rep = [asset defaultRepresentation];  
  37.                 NSString * videoPath = [KCachesPath stringByAppendingPathComponent:fileName];  
  38.                 char constconst *cvideoPath = [videoPath UTF8String];  
  39.                 FILEFILE *file = fopen(cvideoPath, "a+");  
  40.                 if (file) {  
  41.                     const int bufferSize = 11024 * 1024;  
  42.                     // 初始化一個1M的buffer  
  43.                     Byte *buffer = (Byte*)malloc(bufferSize);  
  44.                     NSUInteger read = 0, offset = 0, written = 0;  
  45.                     NSError* err = nil;  
  46.                     if (rep.size != 0)  
  47.                     {  
  48.                         do {  
  49.                             read = [rep getBytes:buffer fromOffset:offset length:bufferSize error:&err];  
  50.                             written = fwrite(buffer, sizeof(char), read, file);  
  51.                             offset += read;  
  52.                         } while (read != 0 && !err);//沒到結尾,沒出錯,ok繼續  
  53.                     }  
  54.                     // 釋放緩衝區,關閉文件  
  55.                     free(buffer);  
  56.                     buffer = NULL;  
  57.                     fclose(file);  
  58.                     file = NULL;  
  59.                 }  
  60.             } failureBlock:nil];  
  61.         }  
  62.     });  
  63. }  

@轉載請標註:轉自iOS界@迷糊小書童   謝謝!
發佈了70 篇原創文章 · 獲贊 37 · 訪問量 29萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章