如何在 Swift 中使用 AVCaptureSession 捕获图片?

Posted

技术标签:

【中文标题】如何在 Swift 中使用 AVCaptureSession 捕获图片?【英文标题】:How to capture picture with AVCaptureSession in Swift? 【发布时间】:2015-04-29 15:37:39 【问题描述】:

我有一个UIViewController,我在其中使用AVCaptureSession 来显示相机,它工作得又好又快。我在这个相机视图的顶部放置了一个UIButton 对象,并为按钮添加了一个IBAction

这就是现在的样子:

现在我想在用户点击按钮时获取当前相机视图的图片:

@IBAction func takePicture(sender: AnyObject) 
    // omg, what do do?!

我不知道该怎么做。我想可能会有这样的事情:

let captureSession = AVCaptureSession()
var myDearPicture = captureSession.takePicture() as UIImage // something like it?

控制器代码的完整链接在这里https://gist.github.com/rodrigoalvesvieira/392d683435ee29305059,希望对您有所帮助

【问题讨论】:

复制现有库DFCamera, TGCameraViewController SUPERB 相机示例代码...drivecurrent.com/devops/… 【参考方案1】:

AVCaptureSession 示例

import UIKit
import AVFoundation
class ViewController: UIViewController 
    let captureSession = AVCaptureSession()
    let stillImageOutput = AVCaptureStillImageOutput()
    var error: NSError?
    override func viewDidLoad() 
        super.viewDidLoad()
        let devices = AVCaptureDevice.devices().filter $0.hasMediaType(AVMediaTypeVideo) && $0.position == AVCaptureDevicePosition.Back 
        if let captureDevice = devices.first as? AVCaptureDevice  

            captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &error))
            captureSession.sessionPreset = AVCaptureSessionPresetPhoto
            captureSession.startRunning()
            stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
            if captureSession.canAddOutput(stillImageOutput) 
                captureSession.addOutput(stillImageOutput)
            
            if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 
                previewLayer.bounds = view.bounds
                previewLayer.position = CGPointMake(view.bounds.midX, view.bounds.midY)
                previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
                let cameraPreview = UIView(frame: CGRectMake(0.0, 0.0, view.bounds.size.width, view.bounds.size.height))
                cameraPreview.layer.addSublayer(previewLayer)
                cameraPreview.addGestureRecognizer(UITapGestureRecognizer(target: self, action:"saveToCamera:"))
                view.addSubview(cameraPreview)
            
        
    
    func saveToCamera(sender: UITapGestureRecognizer) 
        if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) 
            stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) 
                (imageDataSampleBuffer, error) -> Void in
                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
                 UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData), nil, nil, nil)
            
        
    
    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
    

UIImagePickerController 示例

import UIKit

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate 
    let imagePicker = UIImagePickerController()
    @IBOutlet weak var imageViewer: UIImageView!
    override func viewDidLoad() 
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) 
            dismissViewControllerAnimated(true, completion: nil)
             imageViewer.image = image
    
    @IBAction func presentImagePicker(sender: AnyObject) 

        if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerControllerCameraDevice.Front) 

            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
            presentViewController(imagePicker, animated: true, completion: nil)

        
    

【讨论】:

问题是关于 AVCaptureSession?为什么选择 imagePicker? @JunchaoGu 我也添加了一个 AVCaptureSession 示例 我昨天已经完成了 AVSession 的捕获,但无论如何感谢您的回答@Leo Dabus 有没有办法在设备更改为水平位置时更新预览层? @LeoDabus 你能帮帮我吗? ***.com/questions/34574932/…【参考方案2】:

由于 AVCaptureStillImageOutput 已弃用,我创建了另一个在 ios 10 中使用 AVCaptureSessionAVCapturePhotoOutput 的 Swift 示例。请检查 this。

【讨论】:

您可能希望包含示例代码中最相关的部分。

以上是关于如何在 Swift 中使用 AVCaptureSession 捕获图片?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 kotlin native 中使用 swift 库?

如何在 Swift 中使用 Apple 地图 - 你必须使用 C 还是 Swift 可以?

如何在 Swift 中使用 MKPolylineView

如何在 Swift 中使用`syslog`

如何在 swift 项目中使用 TPKeyboardAvoiding?

如何在 Playground 中使用 Swift 包管理器