CameraShot.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //
  2. // CameraShot.swift
  3. // ALCameraViewController
  4. //
  5. // Created by Alex Littlejohn on 2015/06/17.
  6. // Copyright (c) 2015 zero. All rights reserved.
  7. //
  8. import UIKit
  9. import AVFoundation
  10. public typealias CameraShotCompletion = (UIImage?) -> Void
  11. public func takePhoto(_ stillImageOutput: AVCaptureStillImageOutput, videoOrientation: AVCaptureVideoOrientation, cameraPosition: AVCaptureDevice.Position, cropSize: CGSize, completion: @escaping CameraShotCompletion) {
  12. guard let videoConnection: AVCaptureConnection = stillImageOutput.connection(with: AVMediaType.video) else {
  13. completion(nil)
  14. return
  15. }
  16. videoConnection.videoOrientation = videoOrientation
  17. stillImageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { buffer, error in
  18. guard let buffer = buffer,
  19. let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer),
  20. var image = UIImage(data: imageData) else {
  21. completion(nil)
  22. return
  23. }
  24. // flip the image to match the orientation of the preview
  25. if cameraPosition == .front, let cgImage = image.cgImage {
  26. switch image.imageOrientation {
  27. case .leftMirrored:
  28. image = UIImage(cgImage: cgImage, scale: image.scale, orientation: .right)
  29. case .left:
  30. image = UIImage(cgImage: cgImage, scale: image.scale, orientation: .rightMirrored)
  31. case .rightMirrored:
  32. image = UIImage(cgImage: cgImage, scale: image.scale, orientation: .left)
  33. case .right:
  34. image = UIImage(cgImage: cgImage, scale: image.scale, orientation: .leftMirrored)
  35. case .up:
  36. image = UIImage(cgImage: cgImage, scale: image.scale, orientation: .upMirrored)
  37. case .upMirrored:
  38. image = UIImage(cgImage: cgImage, scale: image.scale, orientation: .up)
  39. case .down:
  40. image = UIImage(cgImage: cgImage, scale: image.scale, orientation: .downMirrored)
  41. case .downMirrored:
  42. image = UIImage(cgImage: cgImage, scale: image.scale, orientation: .down)
  43. @unknown default:
  44. fatalError("unknown image orientation")
  45. }
  46. }
  47. completion(image)
  48. })
  49. }