'How to create CGImage from CVPixelBuffer?

I have a simple function to create CGImage from CVPixelBuffer:

if let buffer = (results as? [VNPixelBufferObservation])?.first {
    let pixelBuffer = buffer.pixelBuffer
    let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
    let resultImage = UIImage(ciImage: ciImage)
    return resultImage.cgImage //returns nil
}

But it returns nil. Why?



Solution 1:[1]

The output is nil because you are creating the UIImage instance with a CIImage not CGImage. Here is a way to create a CGImage:

func createCGImage(from pixelBuffer: CVPixelBuffer) -> CGImage? {
   let ciContext = CIContext()
   let ciImage = CIImage(cvImageBuffer: pixelBuffer)
   return context.createCGImage(ciImage, from: ciImage.extent)
}

Solution 2:[2]

Try this one

import VideoToolbox
func createImage(from pixelBuffer: CVPixelBuffer) -> CGImage? {
    var cgImage: CGImage?
    VTCreateCGImageFromCVPixelBuffer(pixelBuffer, options: nil, imageOut: &cgImage)
    return cgImage
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asteroid
Solution 2 Alexander Gaidukov