How can I convert a CVPixelBufferRef to an NSImage or CGImageRef? I need to be able to display the contents of the pixel buffer in a Core Animation Layer.
To convert the buffer to an image, you need to first convert the buffer to an CIImage
, which then can be converted to an NSImage
.
let ciImage = CIImage(cvImageBuffer: pixelBuffer)
let context = CIContext(options: nil)
From here you can go to both GCImage
and NSImage
:
let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)
let cgImage = context.createCGImage(ciImage, from: CGRect(x: 0, y: 0, width: width, height: height))
let nsImage = NSImage(cgImage: cgImage, size: CGSize(width: width, height: height))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With