Episode #147

Core Image

14 minutes
Published on December 4, 2014

This video is only available to subscribers. Get access to this video and 584 others.

In this episode we take a look at Core Image, Apple's image framework for image effects on iOS and Mac OS X.

Episode Links

Creating a Sepia Filter

var cimg = CIImage(image: self.originalImage
let filter = CIFilter(name: "CISepiaTone", withInputParameters: [
    kCIInputImageKey: cimg
])
let output = filter.outputImage

At this point we've applied the filter, but our output image is a CIImage. In order to display it on an image view, we'll have to convert it to a UIImage.

Converting a CIImage to a UIImage

There is a convenience initializer on UIImage that takes a CIImage parameter, however this method doesn't produce a proper image that you can set on a UIImageView. In practice, it will likely stretch the image.

Instead, we can render the image into a CGImage and then create our UIImage from that.

let context = CIContext(options: [:])
let cgimg = context.createCGImage(output, fromRect: output.extent())
let outputImage = UIImage(CGImage: cgimg)

Chaining CIFilters

Our filter, like most CIFilter classes, take an input image and produce an output image. We can use this to chain together different filters to make interesting effects.

var cimg = CIImage(image: self.originalImage)
let filter = CIFilter(name: "CISepiaTone", withInputParameters: [
    kCIInputImageKey: cimg]
)
let sepiaOutput = filter.outputImage

let blur = CIFilter(name: "CIGaussianBlur", withInputParameters: [
    kCIInputImageKey: sepiaOutput,
    kCIInputRadiusKey: 4.0
])

let output = blur.outputImage
let context = CIContext(options: [:])
let cgimg = context.createCGImage(output, fromRect: output.extent())
let outputImage = UIImage(CGImage: cgimg)