2017-03-16 89 views
0

我正在使用类型为AVMediaTypeVideo的Capture-Session分析实况图像。我怎样才能捕捉高品质静态图像(不是低分辨率样品缓冲液),在某些事件=AVFoundation:在视频会话中拍摄高质量静止图像

var videoCaptureDevice: AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) 
var device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) 
var previewLayer: AVCaptureVideoPreviewLayer?  
var captureSession = AVCaptureSession() 
let cameraOutput = AVCapturePhotoOutput() 


//called in view did load 
private func setupCamera() { 

    let input = try? AVCaptureDeviceInput(device: videoCaptureDevice)   
    captureSession.sessionPreset = AVCaptureSessionPreset640x480 
    if self.captureSession.canAddInput(input) { 
     self.captureSession.addInput(input) 
    } 
    self.previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 


    let videoDataOutput = AVCaptureVideoDataOutput() 
    if self.captureSession.canAddOutput(videoDataOutput){ 
     self.captureSession.addOutput(videoDataOutput) 
     videoDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue.main) 
    } 

} 

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) { 

// sampleBuffer is analysed 
// if result is positive, I would like to take a high quality picture 

} 

回答

0

这里有一个小片段,我在我的应用程序使用。我希望这将有助于

private func takePhoto() -> Void 
{ 
    if let videoConnection = stillImageOutput!.connection(withMediaType: AVMediaTypeVideo) 
    { 
     videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait 

     stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) in 
      guard let buffer = sampleBuffer else 
      { 
       return 
      } 

      let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) 
      let dataProvider = CGDataProvider(data: imageData as! CFData) 
      let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, 
       decode: nil, 
       shouldInterpolate: true, 
       intent: CGColorRenderingIntent.defaultIntent) 

      // The image taked 
      let image: UIImage = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right) 

      // Detenemos la captura de imagenes 
      self.captureSession!.stopRunning() 
     }) 
    } 
} 

如果你没有设置你的captureSession变量的sessionPreset属性,默认情况下他的价值观是AVCapture​Session​Preset​High。唯一的预设是比这更高的是AVCaptureSessionPresetPhoto

+0

感谢您的答案!当条件满足时,我打电话给你的方法,并在你的方法中设置AVCapture-Session-Preset为照片(因为我需要高分辨率的照片,但低分辨率的预览)。但是,图像很暗。你知道为什么我可以做到让它获得足够的光线吗? – Pascal