AVCaptureVideoPreviewLayer看起来与捕获的Image不同

时间:2015-02-14 01:40:13

标签: ios swift avfoundation

我的PreviewLayer中显示的图像具有不错的颜色/亮度级别,但是当我捕获图像并将其放入UIImageView时,它看起来非常暗。

为什么光照水平如此不同?

Here's what it looks like in my preview: Here's what it looks like from my capture

这是控制器代码

//Parent Class
class CameraViewController: UIViewController {

  @IBOutlet var photoPreviewView: UIView!
  let captureSession = AVCaptureSession()
  var previewLayer: AVCaptureVideoPreviewLayer?
  var captureDevice: AVCaptureDevice?
  var imageData: NSData?

  override func viewDidLoad() {
    super.viewDidLoad()
    captureSession.sessionPreset = AVCaptureSessionPresetMedium

    let devices = AVCaptureDevice.devices()
    for device in devices {
      // Make sure this particular device supports video
      if (device.hasMediaType(AVMediaTypeVideo)) {
        // Finally check the position and confirm we've got the back camera
        if(device.position == AVCaptureDevicePosition.Back) {
          captureDevice = device as? AVCaptureDevice
        }
      }
    }
    if captureDevice != nil {
      beginSession()
    }
  }

  func captureImage(callback:(NSData)->()) {
    let stillImageOutput = AVCaptureStillImageOutput()
    captureSession.addOutput(stillImageOutput)

    let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo)
    if videoConnection != nil {
      stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) { (imageDataSampleBuffer, error) -> Void in
        callback(AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer))
      }
    } else {
      println("couldn't find video connection")
    }
  }

  func beginSession() {
    var err : NSError? = nil
    let captureDeviceInput = AVCaptureDeviceInput(device: captureDevice, error: &err)
    captureSession.addInput(captureDeviceInput)
    if err != nil {
      println("error: \(err?.localizedDescription)")
    }

    let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    photoPreviewView.layer.addSublayer(previewLayer)

    //FIXME Preview layer is not being positioned as expected. This is an arbitrary hack to make it "look right" on my iphone6
    previewLayer.frame = CGRect(x: -64, y: 0, width: 504, height: 504)


    captureSession.startRunning()
  }
}

class SubmitGuessViewController: CameraViewController {    
  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) -> Void {
    super.prepareForSegue(segue, sender: sender)

    let createImageFromData = {(imageData: NSData) -> () in
      if ( imageData.length > 0 ) {
        let checkGuessViewController = segue.destinationViewController as CheckGuessViewController
        checkGuessViewController.submittedImage = UIImage(data: imageData)
      } else {
        println("Image Data not captured")
      }
    }

    self.captureImage(createImageFromData)
  }

}

0 个答案:

没有答案