swift - CGImage 到 CVPixelBuffer

swift - CGImage to CVPixelBuffer

如何在 swift 中将 CGImage 转换为 CVPixelBuffer

我知道很多问题试图做相反的事情,还有一些 objective C 答案,比如 this one 但我无法让它们在 swift 中工作.这是我得到的最接近的:

func pixelBufferFromCGImage(image: CGImage) -> CVPixelBuffer {
    var pxbuffer: CVPixelBuffer? = nil
    let options: NSDictionary = [:]

    let width =  image.width
    let height = image.height
    let bytesPerRow = image.bytesPerRow

    let dataFromImageDataProvider = image.dataProvider!.data
    let x = CFDataGetBytePtr(dataFromImageDataProvider)

    CVPixelBufferCreateWithBytes(
        kCFAllocatorDefault,
        width,
        height,
        kCVPixelFormatType_32ARGB,
        CFDataGetBytePtr(dataFromImageDataProvider),
        bytesPerRow,
        nil,
        nil,
        options,
        &pxbuffer
    )
    return pxbuffer!;
}

(这不会编译,因为 CVPixelBufferCreateWithBytes 除了一个 UnsafeMutablePointer 而 CFDataGetBytePtr(dataFromImageDataProvider) 是一个 UnsafePointer<UIint8>!

您需要使用 UnsafeMutablePointer,为此,您可以将 CFData 转换为 CFMutableData,然后得到 UnsafeMutablePointer 例如:

let dataFromImageDataProvider = CFDataCreateMutableCopy(kCFAllocatorDefault, 0, image.dataProvider!.data)
let x = CFDataGetMutableBytePtr(dataFromImageDataProvider)