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

Я захватил изображение, используя приведенный ниже код

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 c, люди, которые хотят настроить камеру, например instagram, могут использовать мой код это 100% работает


person Satheeshkumar Naidu    schedule 03.08.2016    source источник


Ответы (2)


// 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 вы можете передать свою переменную.

person ManiaChamp    schedule 03.08.2016
comment
Спасибо за быстрый ответ, но мы переопределяем эти NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer]; - person Satheeshkumar Naidu; 03.08.2016
comment
@SatheeshkumarNaidu: Хорошо, вы можете просто поместить код записи туда, где вы хотите записать изображение в каталог документов в соответствии с вашими потребностями. Я редактирую ответ, если он решит вашу проблему. Отметьте это как ответ, чтобы помочь другим. - person ManiaChamp; 03.08.2016
comment
это не сохраняется.в этом месте что я должен дать - person Satheeshkumar Naidu; 03.08.2016
comment
Если вы получаете NSData своего изображения, вам просто нужно написать, используя приведенный выше код. Вместо переменной imageData поставьте свою переменную. - person ManiaChamp; 03.08.2016
comment
захваченное изображение не отображается в каталоге документов - person Satheeshkumar Naidu; 03.08.2016
comment
Отладьте путь к файлу и попробуйте посмотреть тот же путь, а также проверьте, идет ли он к успеху или ошибке. Если ошибка, проверьте, равны ли ваши данные нулю или нет. - person ManiaChamp; 03.08.2016
comment
NSData *imageData = // Некоторые данные изображения; некоторые данные изображения означают NSURL *url = [NSURL fileURLWithPath:filePath]; это показывает ошибку как неожиданное использование имени интерфейса nsurl ожидаемое выражение, использование необъявленного идентификатора url - person Satheeshkumar Naidu; 03.08.2016
comment
Нет, NSURL *url = [NSURL fileURLWithPath:filePath]; , Это не значит, что. ImageData означает NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer]; - person ManiaChamp; 03.08.2016

person    schedule
comment
В событии нажатия кнопки после захвата/выбора изображения. - person Palanichamy; 03.08.2016
comment
приложение аварийно завершает работу в NSString *filePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@image_name”]]; без продвижения сообщения о сбое в журнале - person Satheeshkumar Naidu; 03.08.2016
comment
Замените этим NSString *filePath = [documentsPath stringByAppendingPathComponent:@image_name]; - person Palanichamy; 03.08.2016
comment
@image_name что мне добавить - person Satheeshkumar Naidu; 03.08.2016
comment
Это просто имя файла. Вы можете указать любую строку. - person Palanichamy; 03.08.2016
comment
Вы тестируете его на устройстве iOS или симуляторе? - person Palanichamy; 03.08.2016
comment
устройство, как мы можем захватить изображение с помощью стимулятора - person Satheeshkumar Naidu; 03.08.2016
comment
Мы не можем захватить изображение в симуляторе. Я спрашиваю о том, где вы проверили, сохраняется ли изображение или нет. Если вы протестируете его на устройстве, изображение не будет храниться в каталоге документов Mac. Он будет храниться в каталоге документов приложения устройства. - person Palanichamy; 03.08.2016
comment
Обратитесь к этому для загрузки каталога документов устройства с Mac. stackoverflow.com/questions/5495508 / - person Palanichamy; 03.08.2016