I wrote a function to apply the filter to a photo. Why the function always returns nil?
func getImage() -> UIImage? {
let openGLContext = EAGLContext(api: .openGLES2)
let context = CIContext(eaglContext: openGLContext!)
let coreImage = UIImage(cgImage: image.cgImage!)
filter.setValue(coreImage, forKey: kCIInputImageKey)
filter.setValue(1, forKey: kCIInputContrastKey)
if let outputImage = filter.value(forKey: kCIOutputImageKey) as? CIImage {
let output = context.createCGImage(outputImage, from: outputImage.extent)
return UIImage(cgImage: output!)
}
return nil
}
When you working with coreImage
in iOS
.You have to considered coreImage classes such as CIFilter, CIContext, CIVector, and CIColor and the input image should be a CIImage
which holds the image data. It can be created from a UIImage.
Note: You haven't mentioned about your filter definition or custom filter that you using.From your code, I can see you trying to change the contrast
of an input image.So, I am testing the code using CIColorControls
filter to adjust the contrast.
func getImage(inputImage: UIImage) -> UIImage? {
let openGLContext = EAGLContext(api: .openGLES2)
let context = CIContext(eaglContext: openGLContext!)
let filter = CIFilter(name: "CIColorControls")
let coreImage = CIImage(image: filterImage.image!)
filter?.setValue(coreImage, forKey: kCIInputImageKey)
filter?.setValue(5, forKey: kCIInputContrastKey)
if let outputImage = filter?.value(forKey: kCIOutputImageKey) as? CIImage {
let output = context.createCGImage(outputImage, from: outputImage.extent)
return UIImage(cgImage: output!)
}
return nil
}
You can call the above func like below.
filterImage.image = getImage(inputImage: filterImage.image!)
Output: