iosiOS点点滴滴iOS移动开发

IOS 批量导照片的实现方法

2015-07-28  本文已影响234人  caiwenshu

需求:

可以从相册中导入100+以上的照片到我们的App中,并且导入的时候需要对图片先压缩,后保存

解决方法:

对于大量的图片使用for each 循环,会在导入10张左右的时候出现内存警告。
所以得使用 dispatch_queue_t来实现串行导入

dispatch_queue_t queue = dispatch_queue_create("yunyou.photo", DISPATCH_QUEUE_SERIAL);
dispatch_group_t group = dispatch_group_create();
    
@autoreleasepool {

for (ALAsset *assetBlock in array) {

    dispatch_block_t task = ^(void) {
        
      @autoreleasepool {
        
        DDLogInfo(@"execute 顺序:%d",[array indexOfObject:assetBlock]);

        //获取资源图片的详细资源信息
        ALAssetRepresentation* representation = [assetBlock defaultRepresentation];
        //获取资源图片的高清图
        CGImageRef imageRef = [representation fullResolutionImage];
        //图片资源原数据
        NSMutableDictionary *imageMetadata = [[representation metadata] mutableCopy];

        UIImage *image = [UIImage imageWithCGImage:imageRef 
                                            scale:representation.scale 
                                            orientation:(UIImageOrientation)representation.orientation];
          
        //修复apple跟ios的旋转不一致的问题
        image = [YYUtils fixOrientationOfImage:image];
        [imageMetadata setImageOrientation:image.imageOrientation];
          
        NSData *defaultData = UIImageJPEGRepresentation(image, 1.0);
          
       //压缩图片
        image = [self compressedImageToUpload:defaultData];

          representation = nil;
          imageMetadata = nil;
          image = nil;

        dispatch_async(dispatch_get_main_queue(), ^{
        
            if (processBlock) {
                processBlock([array indexOfObject:assetBlock],[array count],nil);
            }
        
            DDLogInfo(@"dispatch_get_main_queue execute 顺序%d",
                    [array indexOfObject:assetBlock] );
            
        });
      };
        
    };

   //串行的执行导入
    dispatch_group_async(group, queue, task);
}


//等待所有的图片导入完成
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
DDLogInfo(@"dispatch_group_notify execute ");

//执行完成
completeBlock(nil,[tempTravelPicturesArray count]);
});
    ```
上一篇下一篇

猜你喜欢

热点阅读