swift - CGImage to CVPixelBuffer
Asked Answered
P

1

8

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

Promotion answered 12/7, 2016 at 0:55 Comment(3)
If you know how to do this in Objective-C, why not write this one method in Objective-C and get on with things?Gravy
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)Promotion
So is the question how to turn an UnsafePointer into an UnsafeMutablePointer? Because that's not very difficult.Gravy
M
5

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)
Mission answered 18/11, 2016 at 20:5 Comment(1)
Just to mention that CVPixelBufferCreateWithBytes argument "CFDataGetBytePtr(dataFromImageDataProvider)" should be replaced with "x".Rugged

© 2022 - 2024 — McMap. All rights reserved.