2016-07-12 134 views
2

如何將swift中的CGImage轉換爲CVPixelBufferswift - CGImage到CVPixelBuffer

我知道有很多問題想要做相反的事情,還有一些客觀的C回答,比如this one,但我無法讓他們迅速工作。下面是我得到的最接近:

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

+0

如果你知道如何在Objective-C這樣做,爲什麼不寫THI一種方法_in_ Objective-C並繼續進行下去? – matt

+0

因爲我在Swift中開始一個項目,所以我願意花時間用這種語言來獲取東西,而且我也不瞭解Objective-C(我也不是很願意學習它,我真的有更多到) – Guig

+0

那麼,如何將一個UnsafePointer變成一個UnsafeMutablePointer?因爲這不是很困難。 – matt

回答

0

您需要使用UnsafeMutablePointer,要做到這一點,您可以將CFDataCFMutableData然後得到UnsafeMutablePointer例如:

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