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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28756363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:01:22  来源:igfitidea点击:

How to capture picture with AVCaptureSession in Swift?

iosswiftcameraavcapturesession

提问by rodrigoalvesvieira

I have a UIViewControllerin which I use AVCaptureSessionto show the camera and it is working just fine and fast. I placed a UIButtonobject on top of this camera view and added a IBActionfor the button.

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

This is how it looks like right now:

这是它现在的样子:

my camera app

my camera app

Now I want to get the picture of the current camera view when the user taps the button:

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

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

I have no idea whatsoever on how I can do that. I imagined there could have been something like:

我不知道如何做到这一点。我想象可能有这样的事情:

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

The full link for the controller code is here https://gist.github.com/rodrigoalvesvieira/392d683435ee29305059, hope it helps

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

回答by Leo Dabus

AVCaptureSession Sample

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{ 
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)

        }
    }
}
.hasMediaType(AVMediaTypeVideo) && ##代码##.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 Sample

UIImagePickerController 示例

##代码##

回答by Lawliet

As AVCaptureStillImageOutputis deprecated, I created another Swift example of using AVCaptureSessionand AVCapturePhotoOutputin iOS 10. Check thisout.

正如AVCaptureStillImageOutput已过时,我创建使用的另一示例斯威夫特AVCaptureSessionAVCapturePhotoOutput在IOS 10检查出来。