6

如何快速将 a 转换CGImage为 a CVPixelBuffer

我知道一些试图做相反的问题,以及一些客观的 C 答案,比如这个,但我无法让它们迅速工作。这是我最接近的:

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>!

4

1 回答 1

3

您需要使用 UnsafeMutablePointer,为此,您可以转换CFDataCFMutableData然后获取UnsafeMutablePointer,例如:

let dataFromImageDataProvider = CFDataCreateMutableCopy(kCFAllocatorDefault, 0, image.dataProvider!.data)
let x = CFDataGetMutableBytePtr(dataFromImageDataProvider)
于 2016-11-18T20:05:35.753 回答