在Swift中从AVCaptureSession捕获静止图像 [英] Capture still image from AVCaptureSession in Swift
问题描述
我有一个AVCaptureSession
,可以在UIView中显示实时视频,并且我想将视频流的帧另存为UIImage.我一直在剖析我在互联网上不断看到的代码,但是第一行遇到了麻烦:
I have an AVCaptureSession
that displays live video in a UIView, and I want to save a frame of the video stream as a UIImage. I've been dissecting the code I keep seeing around the internet, but I'm having trouble with the first line:
if let stillOutput = self.stillImageOutput {
// Establish an AVCaptureConnection and capture a still image from it.
}
这给了我错误相机"没有名为"stillImageOutput"的成员.代码取决于能否从输出中获取视频连接.
This gives me the error 'Camera' does not have a member named 'stillImageOutput'. The code depends on being able to get the video connection from the output.
如果有帮助,我可以发布完整的代码块.谢谢!
I can post the full code block if that'd be helpful. Thanks!
推荐答案
一旦您拥有stillImageOutput
,就可以使用以下方法捕获图像
Once you have stillImageOutput
you can use following methods to capture image
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)
比我要获取图像的功能
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()
}
}
}
并停止会话并删除预览层
And to stop session and remove preview layer
func stopSession(){
self.captureSession.stopRunning()
self.previewLayer?.removeFromSuperlayer()
}
这篇关于在Swift中从AVCaptureSession捕获静止图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!