Skip to content

Instantly share code, notes, and snippets.

@4np
Created August 1, 2016 11:37
Show Gist options
  • Save 4np/37c09a59d1e4b69893cf2a4f296959b8 to your computer and use it in GitHub Desktop.
Save 4np/37c09a59d1e4b69893cf2a4f296959b8 to your computer and use it in GitHub Desktop.
Example code to grab a still image (photo) from a mac's FaceTime camera
//
// ImageCaptureManager.swift
// ImageCapture
//
// Created by Jeroen Wesbeek on 29/07/16.
// Copyright © 2016 Jeroen Wesbeek. All rights reserved.
//
import Foundation
import AVFoundation
import AVKit
class ImageCaptureManager {
static let sharedInstance = ImageCaptureManager()
private var captureDevice: AVCaptureDevice?
private var captureSession: AVCaptureSession?
private var stillImageOutput: AVCaptureStillImageOutput?
init() {
do {
// configure photo output
let stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput.outputSettings = [
AVVideoCodecKey: AVVideoCodecJPEG
]
// create capture session
let session = AVCaptureSession()
// add input capture device
let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let videoInput = try AVCaptureDeviceInput(device: captureDevice)
session.addInput(videoInput)
// add still image output
session.sessionPreset = AVCaptureSessionPresetPhoto
if session.canAddOutput(stillImageOutput) {
session.addOutput(stillImageOutput)
}
// commit session
session.commitConfiguration()
// assign locally
self.captureDevice = captureDevice
self.captureSession = session
self.stillImageOutput = stillImageOutput
} catch let error as NSError {
NSLog("Could not initialize image capture session (%@)", error.localizedDescription)
}
}
func takePhoto() {
guard let captureSession = self.captureSession else {
return
}
captureSession.startRunning()
// capture delayed for the exposure to set
NSTimer.scheduledTimerWithTimeInterval(0.15, target: self, selector: #selector(grabStillImage), userInfo: nil, repeats: false)
}
@objc private func grabStillImage() {
guard let captureSession = self.captureSession, stillImageOutput = self.stillImageOutput, videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) else {
return
}
stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) { [weak self] buffer, error in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
self?.saveImage(withData: imageData)
// stop capturing
dispatch_async(dispatch_get_main_queue()) {
captureSession.stopRunning()
}
}
}
private func saveImage(withData data: NSData) {
let image = NSImage(data: data)
if let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first {
// create image file name
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyyMMddHHmmss"
let dateString = formatter.stringFromDate(NSDate())
let destinationPath = "\(documentsPath)/RickRoll-\(dateString).jpg"
// write image
let success = image?.savePNG(destinationPath) ?? false
if !success {
NSLog("Could not save still image from capture device")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment