Auto Save & Capture Pics in Front Cam iOS Swift

时间:2015-07-28 17:11:05

标签: ios iphone swift

Im developing a new app and I'm stuck on a major issue. I need to automatically capture and save a picture of the front cam, in the photos. I used this code but can anyone help me plz to save the image captured. Thank you

    let videoDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
    var captureDevice:AVCaptureDevice

    for device in videoDevices{
        let device = device as! AVCaptureDevice
        if device.position == AVCaptureDevicePosition.Front {
            captureDevice = device

        }
    }

2 个答案:

答案 0 :(得分:0)

试试这个...

import UIKit
import CoreMedia
import CoreVideo
import AVFoundation

class AutocaptureViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AVCaptureVideoDataOutputSampleBufferDelegate
{


    @IBOutlet var cameraImageView: UIImageView!

   // var device: AVCaptureDevice;
var captureSession : AVCaptureSession;
var previewLayer : AVCaptureVideoPreviewLayer;
var cameraImage: UIImage
@IBOutlet var mainImage: UIImageView!
@IBOutlet var tempDrawImage: UIImageView!
@IBOutlet var cameraImg: UIImageView!


var cameraTimer: NSTimer

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

func setupTimer()
{
    snapshot()
    cameraTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(AutocaptureViewController.snapshot), userInfo: nil, repeats: true)
}

func setupCamera() {

    var devices: [AnyObject] = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
    let device = AVCaptureDevice.devices()
    for device: in devices
    {
        if device.position == .Front {
            self.device = device
        }
    }

    //let input = try AVCaptureDeviceInput(device: self.device) as AVCaptureDeviceInput

    var input: AVCaptureDeviceInput = AVCaptureDeviceInput.deviceInputWithDevice(self.device, error: nil)
    var output: AVCaptureVideoDataOutput = AVCaptureVideoDataOutput()
    output.alwaysDiscardsLateVideoFrames = true
   // var queue: dispatch_queue_t
    var queue: dispatch_queue_t = dispatch_queue_create("cameraQueue", DISPATCH_QUEUE_SERIAL)

    //queue = dispatch_queue_create("cameraQueue")
    output.setSampleBufferDelegate(self, queue: queue)
    var key: String = String(kCVPixelBufferPixelFormatTypeKey)
    var value: Int = Int(kCVPixelFormatType_32BGRA)
    var videoSettings: [NSObject : AnyObject] = [
        key : value
    ]

    output.videoSettings = videoSettings

    self.captureSession = AVCaptureSession()
    self.captureSession.addInput(input)
    self.captureSession.addOutput(output)
    self.captureSession.sessionPreset = AVCaptureSessionPresetPhoto
    let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.previewLayer.hidden = true
    // CHECK FOR YOUR APP
    self.previewLayer.frame = CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.width)
    self.previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.Portrait

    // CHECK FOR YOUR APP
    self.view.layer.insertSublayer(self.previewLayer, atIndex: 0)
    // Comment-out to hide preview layer
    self.captureSession.startRunning()

}

func snapshot()
{
    let imageArray: NSMutableArray
    let rect: CGRect = CGRectMake(0, 0, 90, 120)
    UIGraphicsBeginImageContext(rect.size)
    self.cameraImage.drawInRect(rect)
    let picture1: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    let imageData: NSData = UIImagePNGRepresentation(picture1)!
    let img:UIImage = UIImage(data:imageData)!
    imageArray.addObject(img)
    self.cameraImageView.image = img
    // Comment-out to hide snapshot
}

func image(image: UIImage, didFinishSavingWithError error: NSErrorPointer, contextInfo:UnsafePointer<Void>) {
}

 @IBAction func doneBtn(sender: AnyObject)
{
    self.captureSession.stopRunning()

}

答案 1 :(得分:0)

可以使用 UIImagePickerController 作为我对此功能的研发。

如果您想从相机自动捕获图像,则可以使用下面提到的代码。

1. First you need to Add AVFoundation framework in your project. 
Select project -> Add AVFoundation framework in Frameworks, Libraries, and Embedded Content Section


class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate {
    
    let objCaptureSession = AVCaptureSession()
    var objPreviewLayer : AVCaptureVideoPreviewLayer?
    var objCaptureDevice : AVCaptureDevice?
    var objImagePicker = UIImagePickerController()
    var objTimer: Timer?
    var flagRepeatRecording: Bool = false
    var objOutputVolumeObserve: NSKeyValueObservation?
    let objAudioSession = AVAudioSession.sharedInstance()
    
    override func viewDidAppear(_ animated: Bool) {
        if !flagRepeatRecording {
            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                objImagePicker = UIImagePickerController()
                objImagePicker.delegate = self
                objImagePicker.sourceType = .camera
                objImagePicker.allowsEditing = false
                objImagePicker.showsCameraControls = false
                
                //imagePicker.mediaTypes = [kUTTypeMovie as String] // If you want to start auto recording video by camera
            } else {
                debugPrint("Simulator has no camera")
            }
            
            self.present(self.objImagePicker, animated: true, completion: {
                self.objImagePicker.takePicture() // If you want you auto start video capturing then replace this code with take picture() method startVideoCapture()
                
            NotificationCenter.default.addObserver(self, selector: #selector(self.cameraIsReady), name: .AVCaptureSessionDidStartRunning, object: nil)
            
            flagRepeatRecording = true
        }
    }

    @objc func cameraIsReady(notification: NSNotification) {
        DispatchQueue.main.async {
            self.objImagePicker.takePicture()
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//        let tempImage = info[UIImagePickerController.InfoKey.mediaURL] as! NSURL?
//        let pathString = tempImage?.relativePath
        self.dismiss(animated: true, completion: {})
//        UISaveVideoAtPathToSavedPhotosAlbum(pathString!, self, nil, nil)
        
        self.objTimer?.invalidate()
        self.objTimer = nil
    }
}