2013-07-23 4 views
2

Я разрабатываю приложение, которое захватывает фотографии с моей передней камеры iPad. Фотографии идут очень темный. У кого-то есть идея, как решить эту проблему, пожалуйста?iOS: AVFoundation Image Capture Dark

Вот мой код и некоторые explainations:

1) Я инициализировать мой захват сеанса

-(void)viewDidAppear:(BOOL)animated{ 

    captureSession = [[AVCaptureSession alloc] init]; 
    NSArray *devices = [AVCaptureDevice devices]; 
    AVCaptureDevice *frontCamera; 
    for (AVCaptureDevice *device in devices){ 
     if ([device position] == AVCaptureDevicePositionFront) { 
      frontCamera = device; 
     } 
    } 

    if ([frontCamera isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]){ 
     NSError *error=nil; 
     if ([frontCamera lockForConfiguration:&error]){ 
      frontCamera.exposureMode = AVCaptureExposureModeContinuousAutoExposure; 
      frontCamera.focusMode=AVCaptureFocusModeAutoFocus; 
      [frontCamera unlockForConfiguration]; 
     } 
    } 

    NSError *error = nil; 
    AVCaptureDeviceInput *frontFacingCameraDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:frontCamera error:&error]; 
    [captureSession addInput:frontFacingCameraDeviceInput]; 
    [captureSession setSessionPreset:AVCaptureSessionPresetHigh]; 
    captureVideoOutput = [[AVCaptureVideoDataOutput alloc] init]; 
    captureImageOutput =[[AVCaptureStillImageOutput alloc] init]; 
    [captureSession addOutput:captureVideoOutput]; 
    [captureSession addOutput:captureImageOutput]; 

} 

2) Когда пользователь нажимает на кнопку Record, он запускает таймер и просмотреть содержание камеры предварительного просмотра слоя

- (IBAction)but_record:(UIButton *)sender { 

    MainInt = 4; 
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countup) userInfo:nil repeats:YES]; 
    previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:captureSession]; 
    previewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortrait; 
    CGRect rect = CGRectMake(0, 0, self.aView.bounds.size.width, self.aView.bounds.size.height); 
    previewLayer.frame = rect; 
    [self.aView.layer addSublayer:previewLayer]; 
    [captureSession startRunning]; 

} 

3) в конце таймера, снимок сделан и сохранен

- (void)countup { 
    MainInt -=1; 
    if (MainInt == 0) {  
     [timer invalidate]; 
     timer = nil; 

     [captureSession stopRunning]; 
     AVCaptureConnection *videoConnection = nil; 
     for (AVCaptureConnection *connection in captureImageOutput.connections) 
     { 
      for (AVCaptureInputPort *port in [connection inputPorts]) 
      { 
       if ([[port mediaType] isEqual:AVMediaTypeVideo]) 
       { 
        videoConnection = connection; 
        break; 
       } 
      } 
      if (videoConnection) { break; } 
     } 

     [captureImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) 
     { 
      CFDictionaryRef exifAttachments = CMGetAttachment(imageSampleBuffer, kCGImagePropertyExifDictionary, NULL); 
      NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer]; 
      stillImage = [[UIImage alloc] initWithData:imageData]; 
     }]; 

     [captureSession startRunning]; 
     [captureSession stopRunning]; 
    } 
} 

4) Наконец, когда пользователь нажимает на кнопку сохранить, изображение записывается в специальный альбом

- (IBAction)but_save:(UIButton *)sender { 
    UIImage *img = stillImage; 
    [self.library saveImage:img toAlbum:@"mySpecificAlbum" withCompletionBlock:^(NSError *error)]; 
} 

На самом деле, весь код работает правильно, но полученные изображения очень темные ...

+0

где код? –

+0

Я добавил исходный код –

ответ

1

У меня была такая же проблема на IOS 7 5th iPod touch, но не на iPod touch 4-го поколения с iOS 6.1.

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

// Setup camera preview image 
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession]; 
[_previewImage.layer addSublayer:previewLayer]; 

В соответствии с указаниями на https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html#//apple_ref/doc/uid/TP40010188-CH5-SW22

Примечание: Я не исследовал достижения этого без предварительного просмотра

5

Это было со мной тоже, и оказалось, что я пытался захватить слишком рано, и у камеры не было достаточно времени для стабилизации. Я должен был добавить около 0,5 секунд задержки, прежде чем изображения будут нормальной яркостью.

HTH

+0

Это мне очень помогло! Мои изображения не были темными, но большинство из них были не сфокусированы, но это работало как шарм! –