在Swift中从AVCaptureSession捕获静止图像

我有一个AVCaptureSession显示UIView中的实时video,我想保存一个videostream的帧作为UIImage。 我一直在parsing我在互联网上看到的代码,但是我遇到了第一行的麻烦:

 if let stillOutput = self.stillImageOutput { // Establish an AVCaptureConnection and capture a still image from it. } 

这给了我错误“相机”没有名为“stillImageOutput”的成员。 代码取决于能够从输出获得video连接。

如果这有帮助,我可以发布完整的代码块。 谢谢!

一旦你仍然有stillImageOutput你可以使用下面的方法来捕捉图像

  stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG] if captureSession.canAddOutput(stillImageOutput) { captureSession.addOutput(stillImageOutput) } // I had to add timer otherwise quality was messed up in iPad var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("getImage"), userInfo: nil, repeats: false) 

比我的function,以获得形象

 func getImage() { if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) { stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) { (imageDataSampleBuffer, error) -> Void in let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer) // Use your image or store to Album // UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData), nil, nil, nil) self.stopSession() } } } 

并停止会话,并删除预览图层

 func stopSession(){ self.captureSession.stopRunning() self.previewLayer?.removeFromSuperlayer() }