iOS 多選相冊圖片上傳,添加、刪除圖片

DelphiaBill 7年前發布 | 18K 次閱讀 iOS開發 移動開發

通知:在使用下邊的方法的時候出現的問題總結,猿友們看到后請自行更正。

問題一:有人反映打開本demo的時候第一次打不開相冊,必須重新啟動一下才可以打開。

此問題是由于初始化ZYQAssetPickerController懶加載造成的,在使用的時候不使用懶加載創建就可以解決

問題二:本地化圖片

在demo中把圖片確實本地化了一次,發現沒有什么用。

[self.imageDataArray addObject:imageData];

因為這句代碼已經把圖片轉換的字節流放到內存中了,再本地化一次感覺多此一舉

問題三:如果圖片是在iCloud上面的話用ZYQAssetPickerController選擇圖片會崩潰

如果圖片不在本地而是在iCloud上面,需要把圖片下載到本地然后在從本地選取。在第三方.m里面加上下面代碼可以解決,加上之后雖然可以解決但是選擇完圖片在網絡不好的情況下得等一會才可能看到選擇的圖片,方法還得自己寫。

requestOptions.networkAccessAllowed =  YES;

以上是出現的問題,在經過對比之后朋友推薦一個更好的第三方TZImagePickerController,可以去github下載對比一下,感覺瞬間完爆本demo。

上傳圖片功能在app里面很常見,單選圖片,多選圖片,然后還讓展示出來等等,總之要求很多了,以前自己的項目中也用到了這個多選上傳工能,當時寫的比較著急,寫的不是很好,最近閑下來就重新寫了這個需求,先看圖

多選圖片上傳.gif

仔細想一下的話也沒那么麻煩

首先多選相冊里面的圖片的話,我用的是第三方ZYQAssetPickerController 有興趣的可以去github搜一下,因為以前項目中用得是這個。

引入ZYQAssetPickerController,并遵守代理

self.pickerController = [[ZYQAssetPickerController alloc] init];
        _pickerController.maximumNumberOfSelection = 8;
        _pickerController.assetsFilter = ZYQAssetsFilterAllAssets;
        _pickerController.showEmptyGroups=NO;
        _pickerController.delegate=self;
        _pickerController.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            if ([(ZYQAsset*)evaluatedObject mediaType]==ZYQAssetMediaTypeVideo) {
                NSTimeInterval duration = [(ZYQAsset*)evaluatedObject duration];
                return duration >= 5;
            } else {
                return YES;
            }

接下來在需要打開相冊的地方present出來就可以我的里面是這樣的

[self presentViewController:self.pickerController animated:YES completion:nil];

這樣在相冊里面就可以多選圖片了,接下里就是回調了實現代理方法

-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{

在這里處理你選中的圖片

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (int i=0; i<assets.count; i++) {
            ZYQAsset *asset=assets[i];
            [asset setGetFullScreenImage:^(UIImage *result) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //由于iphone拍照的圖片太大,直接存入數組中勢必會造成內存警告,嚴重會導致程序崩潰,所以存入沙盒中
                    //壓縮圖片,這個壓縮的圖片就是做為你傳入服務器的圖片
                    NSData *imageData=UIImageJPEGRepresentation(result, 0.8);
                    [self.imageDataArray addObject:imageData];
                    [self WriteToBox:imageData];
                    //添加到顯示圖片的數組中
                    UIImage *image = [self OriginImage:result scaleToSize:CGSizeMake(80, 80)];
                    [self.imageArray addObject:image];
                    [self.collectionView reloadData];

                });

            }];
        }



    });


    [self dismissViewControllerAnimated:YES completion:^{
        [self.collectionView reloadData];
    }];

以上是代理方法中處理回調過來的圖片,我這里面有兩個數組,一個是imageArray,用于存儲在集合視圖顯示的圖片,一個是imageDataArray,用于存儲壓縮圖片的字節流,我們不可能把選中的圖片直接展示到集合視圖上,iphone拍的照片太大(好幾兆),尺寸也太大,這樣放在我們集合視圖那么小的imageview上面會出問題的,所以先剪裁圖片,同時我把壓縮的imageDataArray里面的原圖存儲在沙盒中,用于以后上傳到服務器

這個是存儲到沙盒中的代碼

#pragma mark --------存入沙盒------------
- (void)WriteToBox:(NSData *)imageData{

    _i ++;
    NSArray *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //獲取Document文件的路徑
    NSString *collectPath = filePath.lastObject;

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:collectPath]) {

        [fileManager createDirectoryAtPath:collectPath withIntermediateDirectories:YES attributes:nil error:nil];

    }
    //    //拼接新路徑
    NSString *newPath = [collectPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Picture_%ld.png",_i]];
    NSLog(@"++%@",newPath);
    [imageData writeToFile:newPath atomically:YES];
}

這是剪裁圖片,用于集合視圖顯示

#pragma mark -----改變顯示圖片的尺寸----------
-(UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);  //size 為CGSize類型,即你所需要的圖片尺寸

    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];

    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return scaledImage;   //返回的就是已經改變的圖片
}

再來就是集合視圖展示了,集合視圖創建就不說了,主要說一下里面的“+”號圖片和刪除

刪除代碼

#pragma mark --------刪除圖片-----------

- (void)deleteImage:(UIButton *)sender{
    NSInteger index = sender.tag - 100;
//    NSLog(@"index=%ld",index);
//    NSLog(@"+++%ld",self.imageDataArray.count);
//    NSLog(@"---%ld",self.imageArray.count);

    //移除顯示圖片數組imageArray中的數據
    [self.imageArray removeObjectAtIndex:index];
    //移除沙盒數組中imageDataArray的數據
    [self.imageDataArray removeObjectAtIndex:index];

    NSArray *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //獲取Document文件的路徑
    NSString *collectPath = filePath.lastObject;
    NSFileManager * fileManager = [NSFileManager defaultManager];
    //移除所有文件
    [fileManager removeItemAtPath:collectPath error:nil];
    //重新寫入
    for (int i = 0; i < self.imageDataArray.count; i++) {
        NSData *imgData = self.imageDataArray[i];
        [self WriteToBox:imgData];
    }

        [self.collectionView reloadData];


}

再來就是里面的“+”號了,這里我用了兩個CollectionViewcell,一個用來展示圖片,一個用來展示“+”號圖片,可能有其他更好的方法 不過我沒想到 ...

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imageArray.count + 1 ;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    AddCollectionViewCell *cell1 = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];

    if (self.imageArray.count == 0) {
        return cell1;

    }else{

    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

        if (indexPath.item + 1 > self.imageArray.count ) {

            return cell1;

        }else{
            cell.imageV.image = self.imageArray[indexPath.item];
            [cell.imageV addSubview:cell.deleteButotn];
            cell.deleteButotn.tag = indexPath.item + 100;
            [cell.deleteButotn addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
        }

        return cell;
    }

}

以上就是主要代碼了,可能寫的有缺點,與各位共勉了

 

 

來自:http://www.jianshu.com/p/a3b1d217c42e

 

 本文由用戶 DelphiaBill 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!