0

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
}
nik3212
  • 392
  • 1
  • 6
  • 18

2 Answers2

1

You never enter the if in that case. Maybe filter.value returns nil OR it isn't a CIImage it returns. Extract it like that and set a breakpoint at if or add a print between:

let value = filter.value(forKey: kCIOutputImageKey)
if let outputImage = value as? CIImage {
    let output = context.createCGImage(outputImage, from: outputImage.extent)
    return UIImage(cgImage: output!)
}

If you need more informations you have to share the filter definition and usage code.

ObjectAlchemist
  • 1,109
  • 1
  • 9
  • 18
1

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:

enter image description here

Joe
  • 8,868
  • 8
  • 37
  • 59