Filters

We can use CoreImage or CI to manipulate images. Applying a filter is a breeze. Here is a function that can be used to generate a filtered version of an image, simply by passing a valid filter name.

Many filters have extra arguments (data) that can be passed, which will affect the final result.
For example, a blur filter applies a level of blurriness.

In the following code snippet, we show how a filter can be applied to an image:

func filter(_ image: UIImage, filter name:String) -> UIImage {
//no filter
if name == "" {
return image
}
//create a context, to draw on
if let eaContext = EAGLContext(api: .openGLES2) {
let context = CIContext(eaglContext: eaContext)
let ciImage = CIImage(image: image)
if let filter = CIFilter(name: name) {
//pass the input image
filter.setValue(ciImage, forKey: kCIInputImageKey)
if let outputImage = filter.outputImage,
let cgImg = context.createCGImage(outputImage,
from: outputImage.extent) {
//create new image
return UIImage(cgImage: cgImg, scale: image.scale,
orientation: image.imageOrientation)
} else {
return UIImage()
}
}
}
return UIImage()
}

This code creates a context and a filter. Then, the filter receives the input image. Next, the code checks the output result from the filter.


All CI filters are executed on the GPU.

You can combine several filters and implement really complex image manipulations.

CoreImage is smart enough to optimize and merge several filters, which reduces the time to apply them.

The output data is used to create a CGImage and then UIImage, which can be used anywhere in the app.
Here are the names of some popular filters:

  • CIPhotoEffectMono
  • CIPhotoEffectTonal
  • CIPhotoEffectNoir
  • CIPhotoEffectFade
  • CIPhotoEffectChrome
  • CIPhotoEffectProcess
  • CIPhotoEffectTransfer
  • CIPhotoEffectInstant
  • CISepiaTone
  • CIGaussianBlur

A full list of filters separated into sections can be found here: https://developer.apple.com/library/content/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html. You can achieve pretty interesting effects when you combine filters or when you pass different values, but you have to experiment. Our app is using a default filter and if we want to add new ones, then we have to modify the code of the YPImagePicker component. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.186.219