Getting a CGImage from CIImage
Swift 3, Swift 4 and Swift 5
Here is a nice little function to convert a CIImage
to CGImage
in Swift.
func convertCIImageToCGImage(inputImage: CIImage) -> CGImage? {
let context = CIContext(options: nil)
if let cgImage = context.createCGImage(inputImage, from: inputImage.extent) {
return cgImage
}
return nil
}
Notes:
CIContext(options: nil)
will use a software renderer and can be quite slow. To improve the performance, useCIContext(options: [CIContextOption.useSoftwareRenderer: false])
- this forces operations to run on GPU, and can be much faster.- If you use
CIContext
more than once, cache it as apple recommends.
See the CIContext
documentation for createCGImage:fromRect:
CGImageRef img = [myContext createCGImage:ciImage fromRect:[ciImage extent]];
From an answer to a similar question: https://stackoverflow.com/a/10472842/474896
Also since you have a CIImage
to begin with, you could use CIFilter
to actually crop your image.