iOS开发之获取系统相册中的图片与视频(内带url转换)

话不多说,直接上代码

[objc]  view plain copy 在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 plain copy 在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. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在iOS开发获取图片二维码的定位,可以使用CoreImage框架。具体步骤如下: 1. 使用CIImage加载图片: ``` CIImage *image = [CIImage imageWithCGImage:image.CGImage]; ``` 2. 创建CIDetector并设置识别类型: ``` CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}]; ``` 3. 识别二维码: ``` NSArray *features = [detector featuresInImage:image]; ``` 4. 遍历识别结果,获取二维码定位: ``` for (CIQRCodeFeature *feature in features) { NSArray *corners = feature.corners; // 获取定位四个角的坐标 // 在图像上绘制定位 UIGraphicsBeginImageContext(imageSize); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor); CGContextSetLineWidth(context, 2.0); CGContextMoveToPoint(context, corners[0].x, corners[0].y); CGContextAddLineToPoint(context, corners[1].x, corners[1].y); CGContextAddLineToPoint(context, corners[2].x, corners[2].y); CGContextAddLineToPoint(context, corners[3].x, corners[3].y); CGContextAddLineToPoint(context, corners[0].x, corners[0].y); CGContextStrokePath(context); UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } ``` 这样就可以在原图上绘制出二维码的定位了。需要注意的是,CIDetector只能识别二维码,如果要识别其他类型的码,需要设置不同的detector类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值