我正在寻找一种将自定义UIImage添加到CMSampleBuffer中的方法,我们可以在AVFoundation中的didOutput sampleBuffer中找到这种方法。我正在开发一个实时流媒体应用程序,并使用sampleBuffer,并将该框架提交给广播公司。然后,我正在尝试在流中添加一个自定义的UIimage,所以我猜测如果在将帧提交给广播程序之前,我可以将UIimage添加到samplebuffer中,那么在实时流视频中添加图像可能是可能的。但是,目前我不确定是否可以将UIImage添加到示例缓冲区,也不确定如何添加它。
一旦我从方法中获得CMSampleBuffer,是否有一种方法将UIImage添加到示例缓冲区?
let myCustomImage = UIImage(named: "customImage")!
var newSampleBuffer: CMSampleBuffer!
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
if let myCVImageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
// add a custom image to the sampleBuffer and put into the newSampleBuffer variable
}
customImageSource?.onSampleBuffer(newSampleBuffer) // onSampleBuffer method is used for submitting the frame to the broadcaster
}发布于 2022-10-21 05:30:27
简单的答案是,您不能在UIImage上应用CMSampleBuffer。您需要从CMSampleBuffer获得CGImage,从UIImage获取CGImage。然后从CGContext创建CVPixelBuffer并使用CGImage填充它。现在您已经将CVPixelBuffer和UIImage应用于它之上了。
func draw(image: UIImage, on sampleBuffer: CMSampleBuffer) {
guard
let cgImage = image.cgImage,
let frame = CMSampleBufferGetImageBuffer(sampleBuffer)
else {
return
}
let flags = CVPixelBufferLockFlags(rawValue: 0)
CVPixelBufferLockBaseAddress(frame, flags)
let context = CGContext(
data: CVPixelBufferGetBaseAddress(frame),
width: CVPixelBufferGetWidth(frame),
height: CVPixelBufferGetHeight(frame),
bitsPerComponent: 8,
bytesPerRow: CVPixelBufferGetBytesPerRow(frame),
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
.union(.byteOrder32Little)
.rawValue
)
let renderBounds = CGRect.zero // put your location here
context?.draw(cgImage, in: renderBounds)
CVPixelBufferUnlockBaseAddress(frame, flags)
}请注意,此方法将精确地在CMSampleBuffer的原始数据上绘制您的图像,因此没有不必要的复制、转换或转换。
https://stackoverflow.com/questions/74148910
复制相似问题