如何在 Swift 中使用 AVCaptureSession 捕获图片? [英] How to capture picture with AVCaptureSession in Swift?

查看:30
本文介绍了如何在 Swift 中使用 AVCaptureSession 捕获图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a UIViewController in which I use AVCaptureSession to show the camera and it is working just fine and fast. I placed a UIButton object on top of this camera view and added a IBAction for the button.

这就是现在的样子:

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

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?

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

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

推荐答案

AVCaptureSession 示例

AVCaptureSession Sample

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 示例

UIImagePickerController Sample

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)

        }
    }
}

这篇关于如何在 Swift 中使用 AVCaptureSession 捕获图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆