自定义相机需要很长时间来保存图像(Swift和AVFoundation)

时间:2016-02-10 06:20:25

标签: ios swift uiimage avfoundation

下面的代码是一个可用的自定义相机。我的目标是在这里拍照并将其调整为正方形。之后,我将图像分配给UIImage,我通过segue传递给后置控制器。 segue最终在图像本身保存之前发生。我知道这是因为segue会在控制台打印UIImage值后几秒钟发生。

class CameraViewController: UIViewController {


@IBOutlet weak var photoButton: UIButton!
@IBOutlet weak var previewView: UIView!


var captureSession: AVCaptureSession?
var stillImageOutput: AVCaptureStillImageOutput?
var previewLayer: AVCaptureVideoPreviewLayer?
var buttonImage = UIImage(named: "CameraButton.png")
var captImage = UIImage()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    photoButton.setBackgroundImage(buttonImage, forState: .Normal)

    captureSession = AVCaptureSession()
    captureSession!.sessionPreset = AVCaptureSessionPresetPhoto

    let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

    var error: NSError?
    var input: AVCaptureDeviceInput!
    do {
        input = try AVCaptureDeviceInput(device: backCamera)
    } catch let error1 as NSError {
        error = error1
        input = nil
    }

    if error == nil && captureSession!.canAddInput(input) {
        captureSession!.addInput(input)

        stillImageOutput = AVCaptureStillImageOutput()
        stillImageOutput!.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
        if captureSession!.canAddOutput(stillImageOutput) {
            captureSession!.addOutput(stillImageOutput)

            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
            previewLayer!.connection?.videoOrientation = AVCaptureVideoOrientation.Portrait
            previewView.layer.addSublayer(previewLayer!)

            captureSession!.startRunning()
        }
    }

}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    previewLayer!.frame = previewView.bounds
}

@IBAction func didPressTakePhoto(sender: UIButton) {

    if let videoConnection = stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo) {
        videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
        stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(sampleBuffer, error) in
            if (sampleBuffer != nil) {
                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                let dataProvider = CGDataProviderCreateWithCFData(imageData)
                let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, CGColorRenderingIntent.RenderingIntentDefault)

                var image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
                //Crop the image to a square
                let imageSize: CGSize = image.size
                let width: CGFloat = imageSize.width
                let height: CGFloat = imageSize.height
                if width != height {
                    let newDimension: CGFloat = min(width, height)
                    let widthOffset: CGFloat = (width - newDimension) / 2
                    let heightOffset: CGFloat = (height - newDimension) / 2
                    UIGraphicsBeginImageContextWithOptions(CGSizeMake(newDimension, newDimension), false, 0.0)
                    image.drawAtPoint(CGPointMake(-widthOffset, -heightOffset), blendMode: .Copy, alpha: 1.0)
                    image = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext()
                    self.captImage = image

                    print(self.captImage)
                }

            }
        })
        self.performSegueWithIdentifier("fromCustomCamera", sender: self)
    }


}

@IBAction func didPressTakeAnother(sender: AnyObject) {
    captureSession!.startRunning()
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "fromCustomCamera"{
        let svc = segue.destinationViewController as! PostViewController
        svc.imageRec = self.captImage
    }
}
}

1 个答案:

答案 0 :(得分:0)

如果要确保在调用完成后执行,则必须在异步函数的完成处理程序内调用performSegueWithIdentifier