8

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.

Drew C
  • 6,258
  • 3
  • 36
  • 50

1 Answers1

1

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))
mangerlahn
  • 4,389
  • 2
  • 23
  • 48