capture image in swift in swift

Here's an example for capturing an image using AVCaptureSession in Swift:

main.swift
import UIKit
import AVFoundation

class ViewController: UIViewController, AVCapturePhotoCaptureDelegate {

    var session: AVCaptureSession?
    var photoOutput: AVCapturePhotoOutput?
    var previewLayer: AVCaptureVideoPreviewLayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a capture session
        session = AVCaptureSession()
        session?.sessionPreset = AVCaptureSession.Preset.photo

        // Select a back camera
        guard let backCamera = AVCaptureDevice.default(for: AVMediaType.video),
              let input = try? AVCaptureDeviceInput(device: backCamera) else {
            print("Unable to access back camera!")
            return
        }

        // Add the input device to the capture session
        session?.addInput(input)

        // Set up a photo output
        photoOutput = AVCapturePhotoOutput()
        photoOutput?.isHighResolutionCaptureEnabled = true

        // Add the photo output to the capture session
        session?.addOutput(photoOutput!)

        // Set up a preview layer
        previewLayer = AVCaptureVideoPreviewLayer(session: session!)
        previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        previewLayer?.frame = view.layer.bounds

        // Add the preview layer to the view
        view.layer.addSublayer(previewLayer!)

        // Start the capture session
        session?.startRunning()
    }

    // Capture a photo
    func capturePhoto() {
        let settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])
        photoOutput?.capturePhoto(with: settings, delegate: self)
    }

    // Handle captured photo
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        guard let imageData = photo.fileDataRepresentation() else {
            return
        }
        let capturedImage = UIImage(data: imageData)
        // Do something with the image
    }
}
1988 chars
61 lines

To capture an image, call the capturePhoto() function. The captured image will be in the capturedImage variable in the photoOutput(_:didFinishProcessingPhoto:error:) delegate method.

gistlibby LogSnag