Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CVPixelBufferRef to NSImage

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.

like image 364
Drew C Avatar asked Apr 25 '12 14:04

Drew C


1 Answers

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))
like image 52
mangerlahn Avatar answered Nov 08 '22 19:11

mangerlahn