iOS camera输出CMSampleBuffer,如何转为UIImage?
第一步:
从sampleBuffer获取CVImageBuffer
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
第二步:
CVImageBuffer转为UIImage
let ciImage = CIImage(cvPixelBuffer: imageBuffer)
let context = CIContext(options: nil)
guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { return nil }
let image = UIImage(cgImage: cgImage, scale: 1.0, orientation: orientation)
具体代码如下
/// Converts an image buffer to a `UIImage`.
/// - Parameters:
/// - imageBuffer: The image buffer which should be converted.
/// - origentation: The orientation already applied to the image.
/// - Returns: A new `UIImage` instance.
public static func createUIImage(from imageBuffer: CVImageBuffer, orientation: UIImage.Orientation) -> UIImage? {
let ciImage = CIImage(cvPixelBuffer: imageBuffer)
let context = CIContext(options: nil)
guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { return nil }
return UIImage(cgImage: cgImage, scale: 1.0, orientation: orientation)
}
//CMSampleBuffer转为UIImage方法
public static func createUIImage(from sampleBuffer: CMSampleBuffer, orientation: UIImage.Orientation) -> UIImage? {
// 获取CMSampleBuffer的核心视频图像缓冲的媒体数据
if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
return Self.createUIImage(from: imageBuffer, orientation: orientation)
}
return nil
}