下面的代码可在iPad mini和iPhone 7上创建当前视频帧的快照,但是在运行iPad Pro时抛出错误是错误的:CIImage initWithCVPixelBuffer:options:失败,因为不支持其像素格式p422 。
存在类似的问题"CIImage initWithCVPixelBuffer:options:" failed because its pixel format p422 is not supported in iOS 10,但不能解决问题。
据我了解,这与视频格式4:2:2有关。有没有解决方法来保存4:2:2?更改视频本身会很麻烦,因为需要编辑许多其他功能。
func snapshotCurrentFrame() -> UIImage? {
guard
let item = playerLayer?.player?.currentItem,
let output = item.outputs.first as? AVPlayerItemVideoOutput,
let pixelBuffer = output.copyPixelBuffer(forItemTime: item.currentTime(), itemTimeForDisplay: nil)
else { return nil }
let rect = CGRect(
x: 0,
y: 0,
width: CVPixelBufferGetWidth(pixelBuffer),
height: CVPixelBufferGetHeight(pixelBuffer)
)
let ciImage = CIImage(cvPixelBuffer: pixelBuffer)
if let cgImage = CIContext().createCGImage(ciImage, from: rect) {
return UIImage(cgImage: cgImage)
} else {
return nil
}
}