2016-10-03 22 views
0

我正在開發相機應用程序。我需要將捕獲的圖像存儲到NSDocumentDirectory中,並將該圖像加載到集合視圖中。我沒有使用數組。我沒有太多關於NSDocument目錄的知識。請任何人都幫我做到這一點。 這是我的代碼,我保存捕獲圖像到nsdocument目錄路徑將捕獲的圖像保存到NSDocument目錄路徑並加載到集合視圖中

-(IBAction)takephoto:(id)sender 
{ 
tapCount += 1; 
AVCaptureConnection *videoConnection = nil; 
for(AVCaptureConnection *connection in StillImageOutput.connections) 
{ 
    for(AVCaptureInputPort *port in [connection inputPorts]) 
    { 
     if ([[port mediaType] isEqual:AVMediaTypeVideo]){ 
      videoConnection =connection; 
      break; 

     } 
    } 
} 


[StillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error){ 


    if (imageDataSampleBuffer!=NULL) { 

     NSData *imageData =[AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer]; 


     self.image = [ UIImage imageWithData:imageData]; 




     //Saving Image in Document directory Path 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentDirectory = paths.firstObject; 
     NSData *imageData1 = UIImagePNGRepresentation(self.image); 

     NSString *imageFolder = @"Photos"; 

     NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init]; 

     [dateFormat setDateFormat:@"yyyMMddHHmmss"]; 
     NSDate *now = [NSDate date]; 
     NSString *theDate = [dateFormat stringFromDate:now]; 
     NSString *myUniqueName = [NSString stringWithFormat:@"Photo-%@.png",theDate]; 

     NSString *imagePath = [NSString stringWithFormat:@"%@/%@",documentDirectory,imageFolder]; 

     BOOL isDir; 
     NSFileManager *fileManager= [NSFileManager defaultManager]; 
     if(![fileManager fileExistsAtPath:imagePath isDirectory:&isDir]) 
      if(![fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:NULL]) 
       NSLog(@"Error: folder creation failed %@", documentDirectory); 

     [[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:@"%@/%@", imagePath, myUniqueName] contents:nil attributes:nil]; 
     [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", imagePath, myUniqueName] atomically:YES]; 
    [self.collection_View reloadData]; 
     } 
}]; 

inViewDidLoad

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

NSString *documentDirectory = paths.firstObject; 
NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentDirectory, @"Photos"]; // image path is same as above 
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fullPath error:nil]; 
     self.fileList=[[NSMutableArray alloc]init]; 
     self.fileName=[[NSMutableArray alloc]init]; 

if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) { 

    for (NSString *filename in dirContents) { 
     NSString *fileExt = [filename pathExtension]; 
     if ([fileExt isEqualToString:@"png"]) { 
      NSString *fullPth = [fullPath stringByAppendingPathComponent:filename]; 
      [self.fileList addObject:fullPth]; 
      [self.fileName addObject:filename]; 
      NSLog(@"File name : %@ ",filename); 
      NSLog(@"fullPth : %@ ",fullPth); 

     } 
    } 


} else { 

    NSLog(@"No Files"); 
} 

這裏是我的代碼,我加載從nsdocumnet目錄路徑圖像轉換成集合視圖。

  -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
    { 
     CollectionViewCell *Cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; 
//Loading images from path 

//Cell.image_View.image = nil; 
NSString *filePath = [self.fileList objectAtIndex:indexPath.row]; 

UIImage *image =[UIImage imageWithContentsOfFile:filePath]; 
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
dispatch_async(queue, ^{ 



    dispatch_async(dispatch_get_main_queue(), ^{ 
     if (image) { 

      Cell.image_View.image = image; 

      // [activityIndicator stopAnimating]; 
      //activityIndicator.hidden = YES; 
      self.collection_View.hidden = NO; 


     } else { 
      Cell.image_View.image = [UIImage imageNamed:@"tours-walk.png"]; 
     } 
    }); 
}); 

Cell.layer.shouldRasterize = true; 
Cell.layer.rasterizationScale = [UIScreen mainScreen].scale; 
return Cell;} 

我已經試過的東西,它走的是圖像和nsdocumentdirectory路徑保存,但它顯示only.if我運行它又把它展示了最新的圖像。請幫助me.check這段代碼前面的圖像和建議任何想法

在此先感謝!

+0

創建路徑字符串的方法可能有助於you.http://stackoverflow.com/questions/2037432/saving-image-to-documents-directory-and-retrieval-for-email-attachment –

+0

謝謝@jecky,我已成功保存圖像,但我不知道要將圖像加載到集合視圖中。請幫助我。 – Saraswathi

+0

您可以從此代碼中獲取圖片。 NSString * filePath = [[NSBundle mainBundle] pathForResource: ofType:]; cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath]]; –

回答

0

正如我理解你的問題,你需要從Gallery/PhotoLibrary中選擇多個圖像,並在Collectionview中加載所選圖像。 如果我是對的,那麼使用這個庫https://github.com/B-Sides/ELCImagePickerController

+0

不,我不要從畫廊或照片庫中選擇多張照片,我需要使用nsdocument目錄路徑在集合視圖中顯示捕獲圖像。 – Saraswathi

+0

保存圖像後是否刷新了數組(如self.fileList和self.fileName)? – Gour

0

當要保存圖像到上面的代碼arrImg文檔目錄

for (UIImage *img in arrImg) 
{ 
    int i=0; 
    NSString *pathName =nil; 
    NSString *fileName = [[self getCurrentDate]stringByAppendingString:[self getCurrentTime]]; 
    fileName =[file_name stringByAppendingPathExtension:@"jpeg"]; 
    NSArray *paths1 =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *basePath =([paths1 count] >i) ? [paths1 objectAtIndex:i] : nil; 
    NSString *path = [basePath stringByAppendingPathComponent:@"Photo"]; 
    //Get Directory in FileManager 
    NSFileManager *fileManager =[NSFileManager defaultManager]; 
    if ([fileManager fileExistsAtPath:path]) 
     return; 
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil]; 
    pathName =[path stringByAppendingPathComponent:file_name]; 
    NSData *imgData =UIImageJPEGRepresentation(image, 0.4); 
    [imgData writeToFile:pathName atomically:YES]; 
    NSMutableArray *arrImgpath = [[NSMutableArray alloc]init]; 
    [arrImgPath addObject:pathName]; 
} 

數組保存imges。

然後,你需要寫信或致電下面的代碼

-(NSString*)getCurrentTime 
{ 
    //Get Current Time for saving Images 
    NSString *path =nil; 
    NSDateFormatter *timeFormatter =[[NSDateFormatter alloc]init]; 
    [timeFormatter setDateFormat:@"HH:mm:ss.SSS"]; 
    NSDate *now = [[NSDate alloc]init]; 

    NSString *str_time = [timeFormatter stringFromDate:now]; 
    NSString *curr_time; 
    curr_time =[str_time stringByReplacingOccurrencesOfString:@"." withString:@""]; 

    path = [NSString stringWithFormat:@"%@",curr_time]; 

    return path; 
} 
-(NSString*)getCurrentDate 
{ 
    NSString *today =nil; 

    NSDateFormatter *dateFormatter1; 
    dateFormatter1 =[[NSDateFormatter alloc]init]; 
    [dateFormatter1 setDateFormat:@"d MMM yyyy"]; 
    NSDate *now =[[NSDate alloc]init]; 
    NSLocale *usLocale =[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"]; 
    [dateFormatter1 setLocale:usLocale]; 
    NSString *str_date =[dateFormatter1 stringFromDate:now]; 
    today=[NSString stringWithFormat:@"%@",str_date]; 
    return today; 
} 

當您從目錄路徑獲取圖像

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    return arrImgpath.count; 
} 

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdentifier = @"cell"; 
    cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; 
    if(cell==nil){ 
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil]; 
    cell = nib[0]; 
    } 
    NSString *localPath=[NSString stringWithFormat:@"%@",[arrImgPath objectAtIndex:indexPath.row]]; 
    //Use either one 
    NSURL *strPathURL=[NSURL fileURLWithPath:localPath]; 
    NSData *data = [NSData dataWithContentsOfURL:strPathURL]; 
    UIImage *imag = [[UIImage alloc] initWithData:data]; 
     //OR 
    UIImage *imag = [UIImage imageWithContentsOfFile:localPath]; 
    cell.img.image = imag; 


    return cell; 
} 

你也需要註冊在viewDidLoad方法將細胞

- (void)viewDidLoad 
{ 
    UINib *cellNib = [UINib nibWithNibName:@"CustomCell" bundle:nil]; 
    [collectionView registerNib:cellNib forCellWithReuseIdentifier:@"cell"]; 
} 
+0

感謝user3182143,在numberofiteminsection什麼我應該返回arrImg計數? – Saraswathi

+0

你應該返回你的arrImgpath(保存的圖像路徑)在numberofItemsinSection – user3182143

+0

好吧,arrImg是保存圖像在數組中,意味着,在這裏我想保存在陣列中的捕獲圖像,我需要做這個過程嗎?\ – Saraswathi

0

試試這個代碼。

NSData *pngData = UIImagePNGRepresentation(image); 

這翻出你所拍攝的圖像的PNG數據。從這裏,您可以將其寫入文件:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory 
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"]; //Add the file name 
[pngData writeToFile:filePath atomically:YES]; //Write the file 

看完後的工作方式相同。構建路徑就像我們剛纔上面那樣的話:

NSData *pngData = [NSData dataWithContentsOfFile:filePath]; 
UIImage *image = [UIImage imageWithData:pngData]; 

讓爲你

- (NSString *)documentsPathForFileName:(NSString *)name 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
    NSString *documentsPath = [paths objectAtIndex:0]; 
    return [documentsPath stringByAppendingPathComponent:name]; 
} 
相關問題