0

I am working on camera app .I need to store the captured image into NSDocumentDirectory and load that images into Collection view. I did using array only .I don't have much knowledge about the NSDocument directory .Please anyone help me to do this. This is my code ,i am saving the capture image into nsdocument directory path

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

Here is my code , i am loading images from the nsdocumnet directory path into collection view .

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

I have tried something ,it is taking the image and saving in nsdocumentdirectory path but it showing the previous images only.if i run it again it is showing the latest image .Please help me.check this code and suggest any idea

Thanks in advance !!!

Saraswathi
  • 5
  • 1
  • 5
  • It may help you.http://stackoverflow.com/questions/2037432/saving-image-to-documents-directory-and-retrieving-for-email-attachment – Jitendra Modi Oct 03 '16 at 09:40
  • Thanks @jecky , i have saved the image successfully , but i don't know to load images into collection view .Please help me. – Saraswathi Oct 03 '16 at 09:45
  • You can get image from this code. NSString * filePath = [[NSBundle mainBundle] pathForResource:ofType:]; cell.backgroundView = [[UIImageView alloc] initWithImage: [UIImage imageWithContentsOfFile: filePath]]; – Jitendra Modi Oct 03 '16 at 09:51
  • If you saved more than one image then this will help you. http://stackoverflow.com/questions/11293690/how-to-display-all-images-from-nsdocument-directory?rq=1 – Jitendra Modi Oct 03 '16 at 10:00

3 Answers3

0

As I understood your problem, you need to select multiple image from Gallery/PhotoLibrary and load the selected image in Collectionview. If I am right, then use this library https://github.com/B-Sides/ELCImagePickerController.

Gour
  • 50
  • 8
  • No , i don't to select multiple picture from gallery or photo library,i need to show the captures image in collection view using nsdocument directory path . – Saraswathi Oct 03 '16 at 09:48
  • Did you refresh the array (like self.fileList and self.fileName) after saving images ? – Gour Oct 03 '16 at 10:09
0

When you want to save image into document directory

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

in above code arrImg is saved imges in array.

Then you need to write or call below code

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

When you fetch the image from directory path

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

Also you need to register the cell in viewDidLoad method

- (void)viewDidLoad
{
   UINib *cellNib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
   [collectionView registerNib:cellNib forCellWithReuseIdentifier:@"cell"];  
}
user3182143
  • 9,459
  • 3
  • 32
  • 39
0

Try this code.

 NSData *pngData = UIImagePNGRepresentation(image);

This pulls out PNG data of the image you've captured. From here, you can write it to a file:

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

Reading it later works the same way. Build the path like we just did above, then:

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

make a method that creates path strings for you

- (NSString *)documentsPathForFileName:(NSString *)name
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);  
    NSString *documentsPath = [paths objectAtIndex:0];
    return [documentsPath stringByAppendingPathComponent:name]; 
}
Himanshu Moradiya
  • 4,769
  • 4
  • 25
  • 49