When I tried to create CGContext from CVImageBuffer with below code
func drawImage(image:CGImage, sampleBuffer: CMSampleBuffer){
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
return
}
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: .zero))
let width = CVPixelBufferGetWidth(pixelBuffer)
let height = CVPixelBufferGetHeight(pixelBuffer)
let context = CGContext(data: CVPixelBufferGetBaseAddress(pixelBuffer),
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer),
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue).union(.byteOrder32Little).rawValue)
context?.draw(image, in: .init(origin: .zero, size: .init(width: 200, height: 200))) // sometime context is nil here
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: .zero))
}
CGContext is nil with below Error
CGBitmapContextCreate: invalid data bytes/row: should be at least 8640 for 8 integer bits/component, 3 components, kCGImageAlphaPremultipliedFirst.
Note: This happens only with specific image buffer size like 4k, etc. And 1080p and 720p works fine.
Appreciate your help in advance!
Have you tried converting the pixelbuffer to CIImage with
imageWithCVPixelBufferand convert it to CGImage. May be the pixelbuffer contains YUV data instead of RGBA.