How to crop an image from AVCapture to a rect seen on the display

In Swift 3:

private func cropToPreviewLayer(originalImage: UIImage) -> UIImage {
    let outputRect = previewLayer.metadataOutputRectConverted(fromLayerRect: previewLayer.bounds)
    var cgImage = originalImage.cgImage!
    let width = CGFloat(cgImage.width)
    let height = CGFloat(cgImage.height)
    let cropRect = CGRect(x: outputRect.origin.x * width, y: outputRect.origin.y * height, width: outputRect.size.width * width, height: outputRect.size.height * height)
    
    cgImage = cgImage.cropping(to: cropRect)!
    let croppedUIImage = UIImage(cgImage: cgImage, scale: 1.0, orientation: originalImage.imageOrientation)
    
    return croppedUIImage
}

Leave a Comment