This is an accelerate based conversion for macOS but maybe it will help you along:
func normaliseImage(inImage: CGImage?) -> CGImage? {
guard
let cgImage = inImage ?? originalnsimage.cgImage(forProposedRect: nil, context: nil, hints: nil) else {return nil}
guard
let format = vImage_CGImageFormat(cgImage: cgImage) else {return nil}
guard
let sourceBuffer = try? vImage_Buffer(cgImage: cgImage, format: format) else {return nil}
defer {sourceBuffer.free()}
bitsperPixel = min(cgImage.bitsPerPixel, 32)
bitsperComponent = min(cgImage.bitsPerComponent, 8)
// Get workable argb image format in return
let argbFormat: vImage_CGImageFormat = {
return vImage_CGImageFormat(bitsPerComponent: bitsperComponent, bitsPerPixel: bitsperPixel, colorSpace: originalColorSpace, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.first.rawValue), renderingIntent: .defaultIntent)!
}()
guard
var destinationBuffer = try? vImage_Buffer(width: Int(sourceBuffer.width), height: Int(sourceBuffer.height), bitsPerPixel: argbFormat.bitsPerPixel) else {return nil}
defer {destinationBuffer.free()}
if let toRgbConverter = try? vImageConverter.make(sourceFormat: format, destinationFormat: argbFormat) {
try? toRgbConverter.convert(source: sourceBuffer, destination: &destinationBuffer)
}
let result = try? destinationBuffer.createCGImage(format: argbFormat)
return result
}