Skip to content

Instantly share code, notes, and snippets.

@darhonbek
Created October 11, 2018 15:39
Show Gist options
  • Save darhonbek/645dfaff3b2fd55e978bf94d5bbb5ac6 to your computer and use it in GitHub Desktop.
Save darhonbek/645dfaff3b2fd55e978bf94d5bbb5ac6 to your computer and use it in GitHub Desktop.
Get UIImage with proper orientation from AVCaptureVideoDataOutputSampleBufferDelegate
func imageFromSampleBuffer(
sampleBuffer: CMSampleBuffer,
videoOrientation: AVCaptureVideoOrientation) -> UIImage? {
if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
let context = CIContext()
var ciImage = CIImage(cvPixelBuffer: imageBuffer)
// FIXME: - change to Switch
if videoOrientation == .landscapeLeft {
ciImage = ciImage.applyingOrientation(3)
} else if videoOrientation == .landscapeRight {
ciImage = ciImage.applyingOrientation(1)
} else if videoOrientation == .portrait {
ciImage = ciImage.applyingOrientation(6)
} else if videoOrientation == .portraitUpsideDown {
ciImage = ciImage.applyingOrientation(8)
}
if let cgImage = context.createCGImage(ciImage, from: ciImage.extent) {
return UIImage(cgImage: cgImage)
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment