Apply effects such as sepia tint, highlight strengthening, and scaling to images.
You can add effects to images by applying Core Image filters to CIImage objects. Figure 1 shows three filters chained together to achieve a cumulative effect:
Apply the sepia filter to tint an image with a reddish-brown hue.
Add the bloom filter to accentuate highlights.
Use the Lanczos scale filter to scale an image down.
Create a Context
CIImage processing occurs in a CIContext object. Creating a CIContext is expensive, so create one during your initial setup and reuse it throughout your app.
Load an Image to Process
The next step is to load an image to process. This example loads an image from the project bundle.
The CIImage object is not itself a displayable image, but rather image data. To display it, you must convert it to another type, such as UIImage.
Apply Built-In Core Image Filters
A CIFilter represents a single operation or recipe for a particular effect. To process a CIImage object, pass it through CIFilter objects. You can subclass CIFilter or draw from the existing library of built-in filters.
Tint Reddish-Brown with the Sepia Filter
Although you can chain filters without separating them into functions, the following example shows how to configure a single CIFilter, the CISepiaTone filter.
To pass the image through the filter, call the sepia filter function.
You can check the intermediate result at any point in the filter chain by converting from CIImage to the user interface-displayable UIImage and assigning the UIImage to a UIImageView in the view hierarchy.
Strengthen Highlights with the Bloom Filter
The bloom filter accentuates the highlights of an image. You can apply it as part of a chain without factoring it into a separate function, but this example encapsulates its functionality in a separate function.
Like the sepia filter, the intensity of the bloom filter’s effect ranges between 0 and 1, with 1 being the most intense effect. The bloom filter has an additional inputRadius parameter to determine how much the glowing regions will expand. Experiment with a range to values to fine tune the effect, or assign the input parameter to a control like a UISlider to allow your users to tweak its values.
Apply the CILanczosScaleTransform to obtain a high-quality downsampling of the image, preserving the original image’s aspect ratio through the CILanczosScaleTransform filter’s input parameter aspectRatio. For built-in Core Image filters, calculate the aspect ratio as the image’s width over height, as in Listing 8.
Like other built-in filters, the CILanczosScale filter also outputs its result as a CIImage.