2016-08-03 2 views
0

Я захватил изображение, используя ниже кодКак сохранить захваченное изображение в в каталог документов

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

при нажатии кнопки

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


}]; 

как сохранить полученное изображение в в каталог документов устройства , может любой орган помочь мне, ответ с кодом оценили, так как я новичок в объекте ios i, люди, которые хотят настроить камеру, такую ​​как instagram, могут использовать мой код, он работает на 100%

ответ

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

Вы можете использовать вышеуказанный код, чтобы сохранить изображение в каталоге документов. Вместо переменной imagedata вы можете передать свою переменную.

+0

Спасибо за быстрое Быстродействие, но мы пересматриваем этот NSData * ImageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation: imageSampleBuffer]; –

+0

@SatheeshkumarNaidu: Хорошо, вы можете просто поместить код для написания, где бы вы ни захотели написать образ в каталог документов в соответствии с вашими потребностями. Я редактирую ответ, если он разрешает вашу проблему. Отметьте это как ответ, чтобы помочь другим. – ManiaChamp

+0

он не получает saved.in tis место, что я должен дать –

1
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 
+0

где я должен добавить это в свой код –

+0

В событии нажатия кнопки после захвата/выбора изображения. – Palanichamy

+0

приложение получает сбой в NSString * filePath = [documentsPath stringByAppendingPathComponent: [NSString stringWithFormat: @ "image_name"]]; с предупреждением об аварийном сообщении в журнале –

Смежные вопросы