天天看點

iOS 取相冊照片/打開相機

最近做了個功能,就是關于打開手機相冊取照片,或者是通過相機照相

作為菜鳥的我,花了兩天的時間才學會,在此分享給大家

基本思路:

1 打開相機:直接打開,通過代理方法取到我們拍下的照片(在進行照片壓縮上傳等操作...)

2 打開相冊:1)、打開系統預設的相冊風格(可使用代理傳遞選擇的照片)   2)、自定義一個相冊(樣式、打開的是哪個相冊、多選等等,這種方法需要自己設定方法傳遞選擇照片,我用的通知)

好,上代碼,具體問題在代碼裡面我再說

!!第一部分:打開相機相冊,回調預覽

//打開相機
-(void)openCamera
{
    //相機是否通路受限制
    if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusRestricted || [ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusDenied) {
        AccessLimitedViewController *limitedVC = [[AccessLimitedViewController alloc]init];
        limitedVC.limiteType =LimiteTypeCamera;
        [self.navigationController pushViewController:limitedVC animated:YES];//自己定義受限制的界面吧,在此不在添加
        return;
    }

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerController.delegate = self;//設定代理,以便取照片
        [self presentViewController:imagePickerController animated:YES completion:NULL];
    }
    else
    {
        [PromoteView showPromoteViewWithContent:@"裝置不支援攝像功能" andRect:CGRectMake((WIDTH-200)/2, HEIGHT/2-25, 200, 50) andTime:2 andObject:self];
    }
    
}
//打開相冊   這裡自定義的相冊
- (void)openPhotoLibrary
{
    
    //相冊是否通路受限
    if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusRestricted || [ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusDenied) {
        AccessLimitedViewController *limitedVC = [[AccessLimitedViewController alloc]init];
        limitedVC.limiteType = LimiteTypePhtoLibrary;
        [self.navigationController pushViewController:limitedVC animated:YES];//同上  自己定義該界面吧
        return;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(photoSelected:) name:@"selectOver" object:nil];
    ShowPhotoViewController*photoVc=[[ShowPhotoViewController alloc]init];
    photoVc.MaxImageNum=CANSelectNum;
    photoVc.numberOfSelectedImage=self.selectedImageArray.count;
    [self.navigationController pushViewController:photoVc animated:YES];
}
//回調,收到選擇完畢的通知,緩存選擇的圖檔
- (void)photoSelected:(NSNotification*)sender{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"selectOver" object:nil];
    if ([[sender object] isKindOfClass:[NSMutableArray class]]) {
        NSMutableArray *array=(NSMutableArray*)[sender object];
        for (ALAsset *asset in array) {
            //用于上傳
            ALAssetRepresentation *representation=asset.defaultRepresentation;
            CGImageRef imageRef=[representation fullScreenImage];
            UIImage *image=[UIImage imageWithCGImage:imageRef];
            [self.selectedImageArray addObject:image];
            
            //用于展示   兩種圖檔的效果不一樣fullScreenImage、thumbnail
            UIImage *imageShow=[UIImage imageWithCGImage:asset.thumbnail];
            [self.ImageArrayToShow addObject:imageShow];
            if (self.ImageArrayToShow.count==CANSelectNum) {
                openPhotoLibrary.hidden=YES;
            }
        }
    }
    [self showPhotoSelected];
    //開始進行圖檔壓縮、上傳
    [self loopForUpImage];
}
//存儲相機拍攝的照片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self.selectedImageArray addObject:image];
        [self.ImageArrayToShow addObject:image];
        [self showPhotoSelected];
        if (self.ImageArrayToShow.count==CANSelectNum) {
            openPhotoLibrary.hidden=YES;
        }
    }];
}


//相機的取消按鈕
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}
//展示照片
-(void)showPhotoSelected
{
    [showBackView removeFromSuperview];
    if (self.ImageArrayToShow.count==0) {
        return;
    }
    showBackView=[[UIView alloc]init];
    showBackView.frame=CGRectMake(0, 290, WIDTH, (self.ImageArrayToShow.count/4+1)*(WIDTH-15-20+40)/4);
    showBackView.backgroundColor=[UIColor yellowColor];
    [self.view addSubview:showBackView];
    
    for (int i=0; i<self.ImageArrayToShow.count; i++) {
        int y=0;
        int j=i;
        if (i>3)
        {
            j=i-4;
            y=1;
        }
        UIImageView *imageShow=[[UIImageView alloc]init];
        imageShow.frame=CGRectMake(10+j*(WIDTH-15)/4, 10+y*(WIDTH-15)/4, (WIDTH-15-20)/4, (WIDTH-15-20)/4);
        imageShow.image=(UIImage *)self.ImageArrayToShow[i];
        imageShow.userInteractionEnabled=YES;
        [imageShow addSubview:[self createDeleteImageButtonWithTag:i]];
        [showBackView addSubview: imageShow];
        //添加圖檔預覽
        imageShow.userInteractionEnabled=YES;
        imageShow.tag=i;
        UITapGestureRecognizer *tapImageToLook=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(lookImage:)];
        [imageShow addGestureRecognizer:tapImageToLook];
    }
}
-(UIButton *)createDeleteImageButtonWithTag:(int)tag//删除標明的圖檔的按鈕
{
    UIButton *button=[[UIButton alloc]init];
    button.frame=CGRectMake((WIDTH-15-20)/4-16, -4, 20, 20);
    button.tag=tag;
    [button setBackgroundImage:[UIImage imageNamed:@"deleteimage"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}
//删除圖檔
-(void)deleteImage:(UIButton *)sender
{
    NSInteger i=sender.tag;
    [self.selectedImageArray removeObjectAtIndex:i];
    [self.ImageArrayToShow removeObjectAtIndex:i];
    [self showPhotoSelected];
    openPhotoLibrary.hidden=NO;
}
//預覽圖檔
-(void)lookImage:(UITapGestureRecognizer *)tap
{
    self.navigationController.navigationBarHidden=YES;
    
    
    //滾動預覽
    scroolShowAllImage =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    scroolShowAllImage.contentSize=CGSizeMake(self.selectedImageArray.count*WIDTH, HEIGHT);
    scroolShowAllImage.backgroundColor=[UIColor blackColor];
    scroolShowAllImage.pagingEnabled=YES;
    [self.view addSubview:scroolShowAllImage];
    // 起始圖檔
    NSInteger indexPath=tap.view.tag;
    scroolShowAllImage.contentOffset=CGPointMake(indexPath*WIDTH, 0);
    
    for (int i=0; i<self.selectedImageArray.count; i++) {
        //尺寸控制
        UIImage *image=[[UIImage alloc]init];
        image=(UIImage *)self.selectedImageArray[i];
        CGFloat imageWidth=image.size.width/2;
        CGFloat imageHeight=image.size.height/2;
        CGFloat scale=imageWidth/imageHeight;//比例縮放
        if(imageWidth>WIDTH)
        {
            imageWidth=WIDTH;
            imageHeight=imageWidth/scale;
        }
        if(imageHeight>HEIGHT)
        {
            imageHeight=HEIGHT;
            imageWidth=imageHeight*scale;
        }
        
        imageView=[[UIImageView alloc]initWithFrame:CGRectMake((WIDTH-imageWidth)/2+WIDTH*i, (HEIGHT-imageHeight)/2, imageWidth, imageHeight)];
        imageView.image=image;
        [scroolShowAllImage addSubview:imageView];
        
        //關閉預覽效果
        imageView.userInteractionEnabled=YES;
        UITapGestureRecognizer *tapImageToClose=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeImage)];
        [imageView addGestureRecognizer:tapImageToClose];
    }
    
}
//關閉預覽
-(void)closeImage
{
    [imageView removeFromSuperview];
    [scroolShowAllImage removeFromSuperview];
    self.navigationController.navigationBarHidden=NO;
}
           

上面基本就是打開相冊或者相機的方法, 有幾個全局變量大家自行設定。另外需要聲明代理

<UIImagePickerControllerDelegate,UIActionSheetDelegate>

幾個屬性 :

@property(nonatomic,strong) NSMutableArray * uploadImageUrl;//存網址

@property(nonatomic,strong)NSMutableArray * selectedImageArray;//存放已選擇照片的數組

@property(nonatomic,strong)NSMutableArray * ImageArrayToShow;//存放已選擇照片的數組_需要展示的

@property(nonatomic,assign)NSInteger currentUpLoadIndex;//目前上傳的第幾張

第二部分: 自定義的相冊 (相冊清單、具體相冊)

//擷取相冊資訊
-(void)getPhotoFromALAssetsLibrary
{
    if(self.photoLibrary ==nil){
        NSMutableArray * array =[[NSMutableArray alloc]init];
        self.photoLibrary =array;
    }
    lib = [[ALAssetsLibrary alloc]init];
    [lib enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        
        if(group != nil){
            //這是一個資料模型( 注釋在下面)
            PhotoLibraryDataModel * libraryData = [[PhotoLibraryDataModel alloc]init];
            /*<p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);">/*!</p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);"> <span style="font-variant-ligatures: no-common-ligatures; color: #004c14">@brief</span> <span style="line-height: normal; font-family: 'PingFang SC';">相冊名字</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);"> */</p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(187, 44, 162);">@property<span style="font-variant-ligatures: no-common-ligatures; color: #000000">(</span>nonatomic<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>strong<span style="font-variant-ligatures: no-common-ligatures; color: #000000">)</span><span style="font-variant-ligatures: no-common-ligatures; color: #703daa">NSString</span><span style="font-variant-ligatures: no-common-ligatures; color: #000000"> *albumName;</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; min-height: 16px;">
</p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; min-height: 16px;">
</p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);">/*!</p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);"> <span style="font-variant-ligatures: no-common-ligatures; color: #004c14">@brief</span> <span style="line-height: normal; font-family: 'PingFang SC';">相冊内照片的數量</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);"> */</p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(187, 44, 162);">@property<span style="font-variant-ligatures: no-common-ligatures; color: #000000">(</span>nonatomic<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>assign<span style="font-variant-ligatures: no-common-ligatures; color: #000000">)</span><span style="font-variant-ligatures: no-common-ligatures; color: #703daa">NSInteger</span><span style="font-variant-ligatures: no-common-ligatures; color: #000000"> number;</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(187, 44, 162);">@property<span style="font-variant-ligatures: no-common-ligatures; color: #000000">(</span>nonatomic<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>strong<span style="font-variant-ligatures: no-common-ligatures; color: #000000">)</span><span style="font-variant-ligatures: no-common-ligatures; color: #703daa">ALAssetsGroup</span><span style="font-variant-ligatures: no-common-ligatures; color: #000000"> * group;   </span><span style="font-variant-ligatures: no-common-ligatures; color: #008400">//</span><span style="line-height: normal; font-family: 'PingFang SC'; color: rgb(0, 132, 0);">相冊對象</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(187, 44, 162);">@property<span style="font-variant-ligatures: no-common-ligatures; color: #000000">(</span>nonatomic<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>assign<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>readwrite<span style="font-variant-ligatures: no-common-ligatures; color: #000000">)</span><span style="font-variant-ligatures: no-common-ligatures; color: #703daa">CGImageRef</span><span style="font-variant-ligatures: no-common-ligatures; color: #000000">  posterImage;  </span><span style="font-variant-ligatures: no-common-ligatures; color: #008400">//</span><span style="line-height: normal; font-family: 'PingFang SC'; color: rgb(0, 132, 0);">相冊頭圖</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(187, 44, 162);">@property<span style="font-variant-ligatures: no-common-ligatures; color: #000000">(</span>nonatomic<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>strong<span style="font-variant-ligatures: no-common-ligatures; color: #000000">)</span><span style="font-variant-ligatures: no-common-ligatures; color: #703daa">NSMutableArray</span><span style="font-variant-ligatures: no-common-ligatures; color: #000000"> * photoArray; </span><span style="font-variant-ligatures: no-common-ligatures; color: #008400">//</span><span style="line-height: normal; font-family: 'PingFang SC'; color: rgb(0, 132, 0);">存放相冊組中所有</span><span style="font-variant-ligatures: no-common-ligatures; color: #008400">ALASSet</span></p>*/
            NSString * groupName = [group valueForProperty:ALAssetsGroupPropertyName];
            libraryData.albumName = groupName;
            libraryData.posterImage = group.posterImage;
            
            NSMutableArray * photoArray = [[NSMutableArray alloc]init];
            
            [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                if(result!= nil){
                    
                    NSString * assetType = [result valueForProperty:ALAssetPropertyType];
                    if([assetType isEqualToString:ALAssetTypePhoto]){
                        [photoArray addObject:result];
                        
                    }else if([assetType isEqualToString:ALAssetTypeVideo]){
                        
                    }else if ([assetType isEqualToString:ALAssetTypeUnknown]){
                        
                    }
                }
                if(index+1 ==group.numberOfAssets){
                    libraryData.group = group;
                    libraryData.photoArray = photoArray;
                    
                    if ([groupName isEqualToString:@"相機膠卷"]) {
                        [self.photoLibrary insertObject:libraryData atIndex:0];
                    } else {
                        [self.photoLibrary addObject:libraryData];
                    }
                    
                    [self creatTableView];
                    
                }
            }];
        }
    } failureBlock:^(NSError *error) {
        
    }];
}
           
//取到照片頭圖,相冊名稱   用表格的形式顯示出來,有兩個參數是我自定義的cell大家忽略即可,隻看頭圖如何取,相冊名如取  
           
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString* identity=@"cell";
    ShowPhotoTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identity];
    if (cell==nil) {
        cell=[[ShowPhotoTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identity];
    }
    PhotoLibraryDataModel * libraryData = [[PhotoLibraryDataModel alloc]init];
    libraryData=(PhotoLibraryDataModel *)[self.photoLibrary objectAtIndex:indexPath.row];
    cell.posterImage.image=[UIImage imageWithCGImage:libraryData.group.posterImage];//頭圖
    cell.albumName.text=libraryData.albumName;//相冊名
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{//表格的點選事件,傳值跳轉 
    PhotoLibraryDataModel * libraryData = [[PhotoLibraryDataModel alloc]init];
    libraryData=(PhotoLibraryDataModel *)[self.photoLibrary objectAtIndex:indexPath.row];
    PhotoDetailViewController *detail=[[PhotoDetailViewController alloc]init];
    detail.MaxImageNum=self.MaxImageNum;
    detail.numberOfSelectedImage=self.numberOfSelectedImage;
    detail.albumDataModel=libraryData;
    [self.navigationController pushViewController:detail animated:YES];
}
           

接下來就相冊詳情,可以看到具體的照片,進行標明等操作,代碼不上了分享了一下連結,感興趣自行下載下傳