Skip to content

Instantly share code, notes, and snippets.

@christianselig
Created March 21, 2020 00:52
Show Gist options
  • Save christianselig/fe987fe817e33add1133fbf6eda5e593 to your computer and use it in GitHub Desktop.
Save christianselig/fe987fe817e33add1133fbf6eda5e593 to your computer and use it in GitHub Desktop.
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