web-dev-qa-db-ja.com

SwiftのAVCaptureSessionで画像をキャプチャする方法は?

カメラを表示するためにUIViewControllerを使用するAVCaptureSessionがありますが、それはうまく機能していて高速です。このカメラビューの上にUIButtonオブジェクトを配置し、ボタンにIBActionを追加しました。

これは、現在どのように見えるかです:

my camera app

ここで、ユーザーがボタンをタップしたときに現在のカメラビューの画像を取得します。

@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 、お役に立てば幸いです

39
rodrigoalves

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)

        }
    }
}
94
Leo Dabus

AVCaptureStillImageOutputは非推奨なので、別のSwift iOS 10でAVCaptureSessionAVCapturePhotoOutputを使用する例を作成しました。チェック this アウト。

7
Lawliet