我正在尝试从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个组件至少应为2560,kCGImageAlphaPremultipliedFirst。”