我正在开发相机应用程序。我需要将捕获的图像存储到NSDocumentDirectory中,然后将这些图像加载到Collection视图中。我只使用过数组。我对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路径中,但它只显示以前的图像。如果我再次运行它会显示最新图像。请帮助我。检查此代码并提出任何想法< / p>
提前致谢!!!
答案 0 :(得分:0)
当我理解您的问题时,您需要从Gallery / PhotoLibrary中选择多个图像并在Collectionview中加载所选图像。 如果我是对的,请使用此库https://github.com/B-Sides/ELCImagePickerController。
答案 1 :(得分:0)
如果要将图像保存到文档目录
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];
}
在上面的代码中,arrImg被保存在数组中。
然后你需要在代码下面写或打电话
-(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"];
}
答案 2 :(得分: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];
}