I'm receiving raw pixels of an image and successfully transforming them into a CGImage with the following function:
func imageFromTexturePixels(raw: UnsafePointer<UInt8>, w: Int, h: Int) -> CGImage? {
// 4 bytes(rgba channels) for each pixel
let bytesPerPixel: Int = 4
// (8 bits per each channel)
let bitsPerComponent: Int = 8
let bitsPerPixel = bytesPerPixel * bitsPerComponent
// channels in each row (width)
let bytesPerRow: Int = w * bytesPerPixel
let cfData = CFDataCreate(nil, raw, w * h * bytesPerPixel)
let cgDataProvider = CGDataProvider(data: cfData!)!
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue)
let image: CGImage! = CGImage(width: w,
height: h,
bitsPerComponent: bitsPerComponent,
bitsPerPixel: bitsPerPixel,
bytesPerRow: bytesPerRow,
space: deviceColorSpace,
bitmapInfo: bitmapInfo,
provider: cgDataProvider,
decode: nil,
shouldInterpolate: false,
intent: CGColorRenderingIntent.defaultIntent)
return image
}
What I really want in the end is a PixelBuffer, so I'm transforming that image into a pixelbuffer using this extension.
Although all this works, it looks a bit inefficient and I'd like to know how to transform the raw pixels directly into a CVPixelBuffer, without converting them into a CGImage before.