简体   繁体   English

在Swift中使用AVFoundation捕获照片

[英]Capture photo with AVFoundation in Swift

I'm building a live filter camera app in swift. 我正在迅速构建一个实时滤镜相机应用程序。

I'm changing from AVCaptureVideoDataOutput() to AVCaptureStillImageOutput() to perform the capturing photo function. 我从AVCaptureVideoDataOutput()更改为AVCaptureStillImageOutput()以执行拍摄照片功能。 After I changed, there is no preview view when I open the app. 更改后,打开应用程序时将没有预览视图。

The capture photo function is working, I can hear the capture sound "Ka" when I click the main group area. 拍摄照片功能正在运行,单击主组区域时可以听到拍摄声音“ Ka”。 There is just no view here. 这里没有风景。

Here is my full code 这是我的完整代码

import Foundation
import UIKit
import AVFoundation
import CoreMedia

let CIHueAdjust = "CIHueAdjust"
let CIHueAdjustFilter = CIFilter(name: "CIHueAdjust", withInputParameters: ["inputAngle" : 1.24])

let Filters = [CIHueAdjust: CIHueAdjustFilter]

let FilterNames = [String](Filters.keys).sort()

class LiveCamViewController :       UIViewController,AVCaptureVideoDataOutputSampleBufferDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
let mainGroup = UIStackView()
let imageView = UIImageView(frame: CGRectZero)
let filtersControl = UISegmentedControl(items: FilterNames)
var videoOutput = AVCaptureStillImageOutput()

override func viewDidLoad()
{
    super.viewDidLoad()

    view.addSubview(mainGroup)
    mainGroup.axis = UILayoutConstraintAxis.Vertical
    mainGroup.distribution = UIStackViewDistribution.Fill

    mainGroup.addArrangedSubview(imageView)
    mainGroup.addArrangedSubview(filtersControl)
    mainGroup.addGestureRecognizer(UITapGestureRecognizer(target: self, action:#selector(LiveCamViewController.saveToCamera(_:))))

    imageView.contentMode = UIViewContentMode.ScaleAspectFit

    filtersControl.selectedSegmentIndex = 0

    let captureSession = AVCaptureSession()
    captureSession.sessionPreset = AVCaptureSessionPresetPhoto

    let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

    do
    {
        let input = try AVCaptureDeviceInput(device: backCamera)

        captureSession.addInput(input)
    }
    catch
    {
        print("can't access camera")
        return
    }

    //get captureOutput invoked
    let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    view.layer.addSublayer(previewLayer)

    videoOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]

    if captureSession.canAddOutput(videoOutput)
    {
        captureSession.addOutput(videoOutput)
    }

    captureSession.startRunning()
}

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!)
{
    guard let filter = Filters[FilterNames[filtersControl.selectedSegmentIndex]] else
    {
        return
    }

    let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
    let cameraImage = CIImage(CVPixelBuffer: pixelBuffer!)

    filter!.setValue(cameraImage, forKey: kCIInputImageKey)

    let filteredImage = UIImage(CIImage: filter!.valueForKey(kCIOutputImageKey) as! CIImage!)
    let fixedImage = correctlyOrientedImage(filteredImage)

    dispatch_async(dispatch_get_main_queue())
    {
        self.imageView.image = fixedImage
    }

}

func correctlyOrientedImage(image: UIImage) -> UIImage {

    UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
    image.drawInRect(CGRectMake(0, 0, image.size.width, image.size.height))
    let normalizedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    let imageRef: CGImageRef = normalizedImage.CGImage!
    let rotatedImage: UIImage = UIImage(CGImage: imageRef, scale: 1.0, orientation: .Right)

    return rotatedImage
}

override func viewDidLayoutSubviews()
{
    mainGroup.frame = CGRect(x: 37, y: 115, width: 301, height: 481)
}

func saveToCamera(sender: UITapGestureRecognizer) {

    videoOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]

    if let videoConnection = videoOutput.connectionWithMediaType(AVMediaTypeVideo) {
        videoOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {
            (imageDataSampleBuffer, error) -> Void in
            let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
            UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData)!, nil, nil, nil)
        }
    }
}

}

Thanks. 谢谢。

If you want to capture photo or video from camera, then you should use UIImagePickerController instead AVFoundation . 如果要从相机捕获照片或视频,则应使用UIImagePickerController而不是AVFoundation Check Applce documentation for more information about it. 查看Applce文档以获取有关它的更多信息。

Update : 更新:

Refer this link . 请参考此链接 It have too many examples of customize imagePickercontroller . 它有太多自定义imagePickercontroller示例。 and you can refer this and this answer of stackobverflow. 您可以参考这个这个 stackobverflow的答案。

Hope this will help :) 希望这会有所帮助:)

The problem might be because you don't have a frame for the previewLayer . 问题可能是因为您没有previewLayer的框架。

Type this: 输入:

previewLayer.frame = self.view.bounds

And also explicitly set the video gravity: (I think this is optional) 并显式设置视频重力:(我认为这是可选的)

previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill // Or choose some other option if you prefer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM