I captured image using below code
AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetMedium;
CALayer *viewLayer = self.vImagePreview.layer;
NSLog(#"viewLayer = %#", viewLayer);
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.frame = self.vImagePreview.bounds;
[self.vImagePreview.layer addSublayer:captureVideoPreviewLayer];
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
// Handle the error appropriately.
NSLog(#"ERROR: trying to open camera: %#", error);
}
[session addInput:input];
[session startRunning];
_stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
[_stillImageOutput setOutputSettings:outputSettings];
[session addOutput:_stillImageOutput];
when i press the button
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in _stillImageOutput.connections)
{
for (AVCaptureInputPort *port in [connection inputPorts])
{
if ([[port mediaType] isEqual:AVMediaTypeVideo] )
{
videoConnection = connection;
break;
}
}
if (videoConnection) { break; }
}
NSLog(#"about to request a capture from: %#", _stillImageOutput);
[_stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
{
CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
if (exifAttachments)
{
// Do something with the attachments.
NSLog(#"attachements: %#", exifAttachments);
}
else
NSLog(#"no attachments");
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
self.vImage.image = image;
_vImage.hidden=YES;
UIStoryboard *storybord=[UIStoryboard storyboardWithName:#"Main" bundle:nil];
shareViewController *shareview=[storybord instantiateViewControllerWithIdentifier:#"share"];
[self presentViewController:shareview animated:YES completion:nil];
shareview.shareimageview.image=image;
NSMutableArray *temparray = [NSMutableArray arrayWithObjects:image,nil];
NSMutableArray *newparsetile=[#[#"you"]mutableCopy];
shareview.newtile=newparsetile;
shareview.selectedimgarray=temparray;
[[NSNotificationCenter defaultCenter] postNotificationName:#"Shareimage" object:image];
}];
how to save the output image in to the device document directory,can any body help me out,answer with code is appreciated,since i am new to the ios objective c,the people who want to customize the camera like instagram can use my code it is 100% working
NSData *pngData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"image_name”]]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
// Saving it to documents direcctory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [directoryPaths objectAtIndex:0];
NSString* filePath = [documentDirectory stringByAppendingPathComponent:#"FileName.png"];
NSData *imageData = // Some Image data;
NSURL *url = [NSURL fileURLWithPath:filePath];
if ([imageData writeToURL:url atomically:YES]) {
NSLog(#"Success");
}
else{
NSLog(#"Error");
}
You can use above code to save an image to documents directory. Instead of imagedata variable you can pass your variable.
Related
I am developing app like camera. This is the method where I am taking photos :
-(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];
}
Now I need to store the captured image in NSDocumentdirectory path and I want to show them in My collection view .
Before this I am saving the image in array and reading the image and I load them in collection view .Please help me to do this.. I don't have much knowledge about this NSDocument directory path .
The path to documents folder is
NSString* appDocumentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
To save the image you have to use
[UIImagePNGRepresentation(image) writeToFile:[appDocumentsFolder stringByAppendingPathComponent:#"/imageName.png"]; atomically:YES];
To use UICollectionView I suggest you to read same articles, like this: https://www.raywenderlich.com/136159/uicollectionview-tutorial-getting-started
I have modified your code, which will save image into Document directory.
NB : Here I assume that, you are getting the image in captureStillImageAsynchronouslyFromConnection method
My Code :
-(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];
//Code to save image into Document directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"SampleImage.png"];
[imageData writeToFile:savedImagePath atomically:NO];
}
}];
}
Hope it helps ...
Happy coding .
I give you detailed answer
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
for(int j=0;j<arrImgPath.count;j++)
{
NSString *localPath=[NSString stringWithFormat:#"%#",[arrImgPath objectAtIndex:j]];
NSURL *strPathURL=[NSURL fileURLWithPath:localPath];
NSData *data = [NSData dataWithContentsOfURL:strPathURL];
UIImage *img = [[UIImage alloc] initWithData:data];
imageView.image = img;
}
I am trying to append CMSampleBufferRefs to an AVAssetWriterInput and I keep getting a crash with error:
[AVAssetWriterInput appendSampleBuffer:] Cannot call method when status is 0
Code:
in viewDidLoad
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [cachePaths firstObject];
NSString *filename = #"test.mp4";
NSString *filePath = [cacheDirectory stringByAppendingPathComponent:filename];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:filePath];
NSError *errors;
assetWriter = [[AVAssetWriter alloc] initWithURL:outputURL fileType:(NSString *)kUTTypeMPEG4 error:&errors];
videoWriteInput = [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeVideo outputSettings:outputSettings];
audioWriteInput = [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeAudio outputSettings:audioSettings];
[audioWriteInput addTrackAssociationWithTrackOfInput:videoWriteInput type:AVTrackAssociationTypeTimecode];
audioWriteInput.expectsMediaDataInRealTime = YES;
videoWriteInput.expectsMediaDataInRealTime = YES;
Record functions
-(void)prepareVideo {
if (![assetWriter startWriting]) {
NSLog(#"%li, %#", assetWriter.status, assetWriter.error.localizedDescription);
}
}
-(void)recordVideo {
recordingVideo = YES;
[assetWriter startSessionAtSourceTime:kCMTimeZero];
}
delegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
if (recordingVideo) {
if ([captureOutput isKindOfClass:[AVCaptureVideoDataOutput class]]) {
if (assetWriter.status != 0) {
[videoWriteInput appendSampleBuffer:sampleBuffer];
}
}
else if ([captureOutput isKindOfClass:[AVCaptureAudioDataOutput class]]) {
if (assetWriter.status != 0) {
[audioWriteInput appendSampleBuffer:sampleBuffer];
}
}
}
}
The status of the AVAssetWriter is 1 so I know this is not the issue..
Did you add the assetwriterinput to the assetwriter?
normally you should do that in the viewdidload method.
[self.assetWriter addInput:self.assetWriterInput];
I have to start recorder first which will record the audio during that i need to record video from camera as well.
Code for audio Recording
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"MyAudioMemo.m4a",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
// Define the recorder setting
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
// Initiate and prepare the recorder
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:nil];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];
[recorder record];
code for video recording
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[picker dismissViewControllerAnimated:YES completion:^
{
if(_isVideo)
{
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
_imageData = [NSData dataWithContentsOfURL:videoURL];
[picker dismissViewControllerAnimated:YES completion:nil];
[ self saveVideo];
}
}];
}
-(void)saveVideo
{
if(_isVideo)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSDateFormatter *formatter;
NSString *dateString;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
dateString = [formatter stringFromDate:[NSDate date]];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#/%#/%#.mp4",_folderName,#"Videos",dateString]];
NSError * error = nil;
NSString *pathVideoThumb = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#/%#/%#",_folderName,#"VideoThumb",dateString]];
[_imageData writeToFile:path options:NSDataWritingAtomic error:&error];
if (error != nil)
{
NSLog(#"Error: %#", error);
return;
}
[self generateThumbImage:pathVideoThumb dataPath:path];
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
_isVideo=NO;
videoCount++;
[videoLabel setText:[NSString stringWithFormat:#"%d %#",videoCount,#"VIDEOS"]];
[videoView setBackgroundColor:[UIColor clearColor]];
});
});
}
}
But when i play the recorded Video it does not contain any sound. The recorded audio is working fine ,I understand that the problem is with the audio session ,Please guide me how should i use audio session to handle this.
Thanks
Based on this code from SamplePhotosApp:
- (void)applyFilterWithName:(NSString *)filterName {
PHContentEditingInputRequestOptions *options = [[PHContentEditingInputRequestOptions alloc] init];
[options setCanHandleAdjustmentData:^BOOL(PHAdjustmentData *adjustmentData) {
return [adjustmentData.formatIdentifier isEqualToString:AdjustmentFormatIdentifier] && [adjustmentData.formatVersion isEqualToString:#"1.0"];
}];
[self.asset requestContentEditingInputWithOptions:options completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
NSURL *url = [contentEditingInput fullSizeImageURL];
int orientation = [contentEditingInput fullSizeImageOrientation];
CIImage *inputImage = [CIImage imageWithContentsOfURL:url options:nil];
inputImage = [inputImage imageByApplyingOrientation:orientation];
// Add filter
CIFilter *filter = [CIFilter filterWithName:filterName];
[filter setDefaults];
[filter setValue:inputImage forKey:kCIInputImageKey];
CIImage *outputImage = [filter outputImage];
// Create editing output
NSData *jpegData = [outputImage aapl_jpegRepresentationWithCompressionQuality:0.9f];
PHAdjustmentData *adjustmentData = [[PHAdjustmentData alloc] initWithFormatIdentifier:AdjustmentFormatIdentifier formatVersion:#"1.0" data:[filterName dataUsingEncoding:NSUTF8StringEncoding]];
PHContentEditingOutput *contentEditingOutput = [[PHContentEditingOutput alloc] initWithContentEditingInput:contentEditingInput];
[jpegData writeToURL:[contentEditingOutput renderedContentURL] atomically:YES];
[contentEditingOutput setAdjustmentData:adjustmentData];
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *request = [PHAssetChangeRequest changeRequestForAsset:self.asset];
request.contentEditingOutput = contentEditingOutput;
} completionHandler:^(BOOL success, NSError *error) {
if (!success) {
NSLog(#"Error: %#", error);
}
}];
}];
}
I have created my own implementation of applying filters to images. My code:
- (void)saveAsset:(PHAsset *)asset withEdits:(NSDictionary *)edits withCompletion:(successBlock)block {
PHContentEditingInputRequestOptions *options = [[PHContentEditingInputRequestOptions alloc] init];
[options setCanHandleAdjustmentData:^BOOL(PHAdjustmentData *adjustmentData) {
return [adjustmentData.formatIdentifier isEqualToString:#"myID"] && [adjustmentData.formatVersion isEqualToString:#"1.0"];
}];
[asset requestContentEditingInputWithOptions:options completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
NSURL *fullImageURL = [contentEditingInput fullSizeImageURL];
UIImage *fullSizeImage = [UIImage imageWithContentsOfFile:[fullImageURL path]];
UIImage *editedImage = [EngineImageFilters applyEffects:edits[#"filters"] toImages:#[fullSizeImage] withValue:#(ImageFilterValueTypeCustom)][0];
NSData *imageData = UIImageJPEGRepresentation(editedImage, 1.0);
NSData *editData = [NSJSONSerialization dataWithJSONObject:edits options:0 error:nil];
PHAdjustmentData *adjustmentData = [[PHAdjustmentData alloc] initWithFormatIdentifier:#"profcam" formatVersion:#"1.0" data:editData];
PHContentEditingOutput *output = [[PHContentEditingOutput alloc] initWithContentEditingInput:contentEditingInput];
[imageData writeToURL:[output renderedContentURL] atomically:YES];
[output setAdjustmentData:adjustmentData];
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *request = [PHAssetChangeRequest changeRequestForAsset:asset];
request.contentEditingOutput = output;
} completionHandler:^(BOOL success, NSError *error) {
if (block) {
block(success, error);
}
}];
}];
}
My snippets will cause a crash, due to many values being nil. requestContentEditingWithOptions:completionHandler method gives nil for PHContentEditingInput, which causes many problems like file url being nil and so on. It also seems that the setCanHandleAdjustmentData block is never called - maybe this is the reason PHContentEditingInput is nil. Anyways, how should I fix this problem?
hi I am using the AVCam Liberary for automatic image capturing.I dont want to
save the image in photo libriary I want to save the image in document directory .it saves the image but having problem when i
load this image gives access bad.
- (void) captureStillImage
{
AVCaptureConnection *stillImageConnection = [AVCamUtilities connectionWithMediaType:AVMediaTypeVideo fromConnections:[[self stillImageOutput] connections]];
if ([stillImageConnection isVideoOrientationSupported])
[stillImageConnection setVideoOrientation:orientation];
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:stillImageConnection
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
ALAssetsLibraryWriteImageCompletionBlock completionBlock = ^(NSURL *assetURL, NSError *error) {
if (error) {
if ([[self delegate] respondsToSelector:#selector(captureManager:didFailWithError:)]) {
[[self delegate] captureManager:self didFailWithError:error];
}
}
};
if (imageDataSampleBuffer != NULL) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
UIImage *image = [[UIImage alloc] initWithData:imageData];
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/Image.jpg", docDirectory];
NSData *imageDataToSave = [NSData dataWithData:UIImagePNGRepresentation(image)];
[imageDataToSave writeToFile:filePath atomically:YES];
//[self saveImage:image];
completionBlock:completionBlock];
[image release];
[library release];
}
else
completionBlock(nil, error);
if ([[self delegate] respondsToSelector:#selector(captureManagerStillImageCaptured:)]) {
[[self delegate] captureManagerStillImageCaptured:self];
}
}];
}
and loading the image
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/Image.jpg", docDirectory];
UIImage* loadedImage = [UIImage imageWithContentsOfFile:filePath];
[ImageView setImage:loadedImage];
when this loadedImage is assign to any UIImage
While writing the file try -
[UIImagePNGRepresentation(self.imageView.image) writeToFile:pngPath atomically:YES];