2016-10-03 8 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;} 

私は何かを試してみました、最新の画像は、このコードをme.check手助けしなさい見せている画像を撮影し、nsdocumentdirectoryパスに保存しますが、私は再びそれを実行しonly.ifそれは、前の画像を表示して、任意のアイディアを提案する

ありがとうございます!!!

+0

パス文字列を作成する方法を作ります/ 2037432 /画像を保存する画像ファイルとディレクトリを取得して電子メールに添付する –

+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を保存されます。

は、その後、あなたがディレクトリパス

-(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; 
} 

から画像を取得すると書いたり、コード

-(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; 
} 

下に呼び出す必要がある。また、あなたはviewDidLoadメソッド

- (void)viewDidLoad 
{ 
    UINib *cellNib = [UINib nibWithNibName:@"CustomCell" bundle:nil]; 
    [collectionView registerNib:cellNib forCellWithReuseIdentifier:@"cell"]; 
} 
でセルを登録する必要があります
+0

ありがとうuser3182143、numberofiteminsectionで私は何を返すべきですか? – Saraswathi

+0

あなたはnumberofItemsinSectionにarrImgpath(保存された画像パス)を返すべきです – user3182143

+0

Ok、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 

は、後で同じように動作します。私たちは上記のようにやった、その後、パスを構築します。//stackoverflow.com/questions:

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

はそれがyou.http助けるかもしれないあなたのための

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