Search code examples
swiftcgimagecvpixelbuffer

swift - CGImage to CVPixelBuffer


How can I convert a CGImage to a CVPixelBuffer in swift?

I'm aware of a number of questions trying to do the opposite, and of some objective C answers, like this one but I could not get them to work in swift. Here's the closest I've got:

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

(this doesn't compile because CVPixelBufferCreateWithBytes excepts an UnsafeMutablePointer and CFDataGetBytePtr(dataFromImageDataProvider) is an UnsafePointer<UIint8>!)


Solution

  • You need to use UnsafeMutablePointer, to do that, you can transform CFData to CFMutableData and then get UnsafeMutablePointer for example:

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