Created
March 21, 2020 00:52
-
-
Save christianselig/fe987fe817e33add1133fbf6eda5e593 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func cgImageFromSampleBuffer(_ buffer: CMSampleBuffer) -> CGImage? { | |
guard let pixelBuffer = CMSampleBufferGetImageBuffer(buffer) else { | |
return nil | |
} | |
CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly) | |
let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) | |
let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer) | |
let width = CVPixelBufferGetWidth(pixelBuffer) // Preferably I'd like to hardcode this width | |
let height = CVPixelBufferGetHeight(pixelBuffer) // and this height | |
let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)! | |
let image = context.makeImage()! | |
CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) | |
return image | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment