iOS取照片库的缩略图和大图

来源:互联网 发布:上海数据交易中心待遇 编辑:程序博客网 时间:2024/05/02 00:30

iOS取照片库的缩略图和大图

1.取出照片库的照片

1.取出缩略图相对简单,不用重新存储:[UIImage imageWithCGImage:[result thumbnail]]   2.取出原图,需要根据url转存为data格式,再根据路径取出(下面详细看代码)

示例代码完整版

#import "ViewController.h"#import "LargePhotoViewController.h"#import <AssetsLibrary/AssetsLibrary.h>#define  KOriginalPhotoImagePath   [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"OriginalPhotoImages"]#define kImgUrl     @"photoUrl"#define kThumbnail  @"thumbPic"#define kImgName    @"imgName"@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>//@property (weak, nonatomic) IBOutlet UIImageView *imgView;@property (strong, nonatomic) NSMutableArray *photoArrM;@property (strong, nonatomic) NSMutableArray *assets;@property (strong, nonatomic) ALAssetsLibrary *assetsLibrary;@property (strong, nonatomic) NSMutableArray *photoArrURL;@property (assign, nonatomic) NSInteger count;@property (strong, nonatomic) UITableView *tableView;@end
@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    _photoArrM = [NSMutableArray array];    _assets = [NSMutableArray array];    _photoArrURL = [NSMutableArray array];    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, self.view.bounds.size.height-200) style:UITableViewStyleGrouped];    self.tableView.delegate = self;    self.tableView.dataSource = self;    [self.view addSubview:self.tableView];    //生成整个photoLibrary句柄    _assetsLibrary = [[ALAssetsLibrary alloc]init];    [self getPhotoPath];}- (IBAction)getAlbum:(UIButton *)sender {    if (self.photoArrURL.count>0) {        [self.tableView reloadData];    }}
-(void)reloadImage{    NSLog(@"+++");}-(void)getPhotoPath{    //获取所有group    __block ViewController *photoVC = self;    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{        [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {            ALAssetsFilter *onlyPhotoFilter = [ALAssetsFilter allPhotos];            [group setAssetsFilter:onlyPhotoFilter];            if (group != nil) {                self.count= group.numberOfAssets;                [photoVC.photoArrM addObject:group];                if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:@"Camera Roll"]) {                dispatch_async(dispatch_get_main_queue(), ^{                    [self reloadImage];                    });                }            }else{                [photoVC.photoArrM enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {                    if ([[(ALAssetsGroup *)obj valueForProperty:ALAssetsGroupPropertyName] isEqualToString:@"Camera Roll"]) {                        [obj enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {                            if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {                                if ([result thumbnail]) {                                    NSDate *date= [result valueForProperty:ALAssetPropertyDate];                                    UIImage *img = [UIImage imageWithCGImage:[result thumbnail]];                                    NSString *fileName = [[result defaultRepresentation] filename];                                    NSURL *url = [[result defaultRepresentation] url];                                    int64_t fileSize = [[result defaultRepresentation] size];                                    NSLog(@"date = %@",date);                                    NSLog(@"fileSize = %lld",fileSize);                                    NSDictionary *dic = @{kImgUrl:url,kThumbnail:img,kImgName:fileName};                                    [self.photoArrURL addObject:dic];                                    [self imageWithUrl:url withFileName:fileName];                                }                                dispatch_async(dispatch_get_main_queue(), ^{                                });                            }                        }];                    }                }];            }        } failureBlock:^(NSError *error) {            NSLog(@"error:%@",error);            NSString *errorMessage = @"";            switch ([error code]) {                case ALAssetsLibraryAccessUserDeniedError:                case ALAssetsLibraryAccessGloballyDeniedError:                    errorMessage = @"用户拒绝访问相册,请在<设置>中开启";                    break;                default:                    break;            }            dispatch_async(dispatch_get_main_queue(), ^{                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"错误,无法访问!"                                                                   message:errorMessage                                                                  delegate:self                                                         cancelButtonTitle:@"确定"                                                         otherButtonTitles:nil, nil];                [alertView show];            });        }];    });}
#pragma mark -- 相册的大图需要转存// 将原始图片的URL转化为NSData数据,写入沙盒- (void)imageWithUrl:(NSURL *)url withFileName:(NSString *)fileName{    // 通过是否存在文件路径,判断是否需要转化    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];    // 创建存放原始图的文件夹--->OriginalPhotoImages    NSFileManager * fileManager = [NSFileManager defaultManager];    if (![fileManager fileExistsAtPath:KOriginalPhotoImagePath]) {        [fileManager createDirectoryAtPath:KOriginalPhotoImagePath withIntermediateDirectories:YES attributes:nil error:nil];    }    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        if (url) {            [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {                ALAssetRepresentation *rep = [asset defaultRepresentation];                Byte *buffer = (Byte*)malloc((unsigned long)rep.size);                NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:((unsigned long)rep.size) error:nil];                NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];                NSString * imagePath = [KOriginalPhotoImagePath stringByAppendingPathComponent:fileName];                [data writeToFile:imagePath atomically:YES];            } failureBlock:nil];        }    });    NSLog(@"path:==%@",KOriginalPhotoImagePath);}
#pragma mark -- tableView- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return self.photoArrURL.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *cellID = @"cellID";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];    if (nil == cell) {        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];    }    cell.imageView.image = [[self.photoArrURL objectAtIndex:indexPath.row] objectForKey:kThumbnail];    cell.selectionStyle = UITableViewCellSelectionStyleNone;    return cell;}-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return 100.0f;}-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    LargePhotoViewController *largeVC = [[LargePhotoViewController alloc]init];    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"OriginalPhotoImages"];    largeVC.largeImg = [UIImage imageWithContentsOfFile:[path stringByAppendingPathComponent:[self.photoArrURL[indexPath.row] objectForKey:kImgName]]];    [self presentViewController:largeVC animated:YES completion:nil];}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

大图展示

#import <UIKit/UIKit.h>@interface LargePhotoViewController : UIViewController@property(strong, nonatomic) UIImage *largeImg;@end
#import "LargePhotoViewController.h"@interface LargePhotoViewController ()@property(nonatomic, strong) UIImageView *imgView;@end@implementation LargePhotoViewController- (void)viewDidLoad {    [super viewDidLoad];    _imgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 30, self.view.bounds.size.width-20, self.view.bounds.size.height-60)];    if (self.largeImg) {        self.imgView.image = self.largeImg;    }    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissVc)];    [self.imgView addGestureRecognizer:tap];    self.imgView.userInteractionEnabled = YES;    self.imgView.backgroundColor = [UIColor whiteColor];    [self.view addSubview:self.imgView];    self.view.backgroundColor = [UIColor whiteColor];}-(void)dismissVc{    self.imgView.image = nil;    [self dismissViewControllerAnimated:YES completion:nil];}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end
取出视频与取出照片类似感谢以及参考资料:http://www.2cto.com/kf/201409/331138.html
0 0
原创粉丝点击