我正在尝试从 CMSampleBuffer 创建 UIImage。以下代码适用于来自后置摄像头的样本缓冲区,但不适用于前置摄像头。使用前置摄像头时,CGContext初始化失败,即CGContext构造函数返回nil。我怀疑我需要使用正确的位图信息,但是有很多组合。
func convert(buffer: CMSampleBuffer) -> UIImage? {
guard let imageBuffer = CMSampleBufferGetImageBuffer(buffer) else { return nil }
CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags.readOnly)
let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
let width = CVPixelBufferGetWidth(imageBuffer)
let height = CVPixelBufferGetHeight(imageBuffer)
let colorSpace = CGColorSpaceCreateDeviceRGB()
var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Little.rawValue
bitmapInfo |= CGImageAlphaInfo.premultipliedFirst.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo)
guard let quartzImage = context?.makeImage() else { return nil }
CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags.readOnly)
let image = UIImage(cgImage: quartzImage)
return image
}
它伴随着以下错误:“CGBitmapContextCreate:无效数据字节/行:对于 8 个整数位/分量、3 个分量、kCGImageAlphaPremultipliedFirst,应至少为 2560。”