2017-03-16 80 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