快速的照片捕获黑色图像

时间:2015-07-08 19:13:28

标签: ios swift avfoundation

我尝试使用Swift设置AVFoundation照片捕获。预览窗口工作正常但是当我按下按钮捕捉照片时,应用程序启动后拍摄的第一张照片是完全黑色的。我在相同的应用实例中运行的任何后续图片都能正常工作,但第一张图片总是只是一个黑色矩形。拍摄照片时,预览图层也会闪烁黑色。这是我用于相机的代码:

import UIKit
import AVFoundation

class photoCaptureViewController: UIViewController {

let session                     : AVCaptureSession = AVCaptureSession()
var previewLayer                : AVCaptureVideoPreviewLayer!
var output = AVCaptureStillImageOutput()
var capturedImage               : UIImage!

override func viewDidLoad() {
    super.viewDidLoad()

  let device = getFrontCamera()
  var error   : NSError? = nil

  let input   : AVCaptureDeviceInput? = AVCaptureDeviceInput.deviceInputWithDevice(device, error: &error) as? AVCaptureDeviceInput

  if input != nil {
    session.addInput(input)
  }else{
    println(error)
  }

  session.sessionPreset = AVCaptureSessionPresetPhoto

  previewLayer = AVCaptureVideoPreviewLayer.layerWithSession(session) as! AVCaptureVideoPreviewLayer
  previewLayer.frame = CGRectMake(0, 0, 300, 300)
  previewLayer.setAffineTransform( CGAffineTransformTranslate(CGAffineTransformMakeScale(0.33, 0.33), -375, -480) )
  previewLayer.position = CGPointMake((photoButton.layer.position.x + 70), (photoButton.layer.position.y - 45))

  previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

  self.view.layer.addSublayer(previewLayer)

  self.setPreviewOrientation()

  session.startRunning()

}

func setPreviewOrientation() {
  let previewLayerConnection: AVCaptureConnection = self.previewLayer.connection
  let orientation = AVCaptureVideoOrientation(rawValue: UIDevice.currentDevice().orientation.rawValue)
  previewLayerConnection.videoOrientation = orientation!
}

@IBAction func photoButtonPressed(sender: UIButton)
{

  output.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]

  if session.canAddOutput(output)
  {
    session.addOutput(output)
  }

  var videoConnection = output.connectionWithMediaType(AVMediaTypeVideo)

  if videoConnection != nil {
    output.captureStillImageAsynchronouslyFromConnection(output.connectionWithMediaType(AVMediaTypeVideo))
      { (imageDataSampleBuffer, error) -> Void in
        self.capturedImage = UIImage(data: AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer))

        UIImageWriteToSavedPhotosAlbum(self.capturedImage, self,nil, nil)

    }}


}

func getFrontCamera() -> AVCaptureDevice{
  var result : AVCaptureDevice!
  var devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
  for device in devices{
    if (device.position == AVCaptureDevicePosition.Front) {
      result = device as! AVCaptureDevice
    }
  }
  return result
}

}

1 个答案:

答案 0 :(得分:1)

通过移动

来解决这个问题
 output.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]

if session.canAddOutput(output)
{
  session.addOutput(output)
}

在viewDidLoad下,而不是在照片捕捉功能中。