7

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

Guig
  • 9,891
  • 7
  • 64
  • 126
  • If you know how to do this in Objective-C, why not write this one method _in_ Objective-C and get on with things? – matt Jul 12 '16 at 01:01
  • Because I'm starting a project in Swift and I'm willing to put the time to get things in that language, and I don't know Objective-C as well (nor am I willing to learn it more that I really have to) – Guig Jul 12 '16 at 01:14
  • So is the question how to turn an UnsafePointer into an UnsafeMutablePointer? Because that's not very difficult. – matt Jul 12 '16 at 02:00

1 Answers1

4

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)
Joe
  • 8,868
  • 8
  • 37
  • 59
Carolina
  • 437
  • 3
  • 18
  • Just to mention that CVPixelBufferCreateWithBytes argument "CFDataGetBytePtr(dataFromImageDataProvider)" should be replaced with "x". – manikal Apr 01 '22 at 17:14