How would you invert the colors of an image in Swift?

As part of the first lessons associated with Project 1, “Pitch Perfect” in Udacity’s iOS Swift course, we (the students) are asked to blog about a specific topic related to how things are done in Apple’s new programming language, Swift. As you can see from the title, I’ve chosen to write about how to invert the colors of an image.

First, I’d like to discuss how to actually load an image onto the screen. The first step would be to open up your Storyboard and add a UIImageView object to the view. This object will allow you to show images (adhering to UIKit’s UIImage class) within its bounds.

The next step would be to go into your project’s Images.xcassets and drag an image into the editor. Let’s call this image “theImage.png”.

Once the image is in our project, we can set the UIImageView’s image attribute (in Storyboard’s “Attribute Inspector”) to our desired image. Next, we must connect the UIImageView to our viewController code by opening the Assistant editor mode and holding CTRL + drag from UIImageView to above the viewDidLoad function. This ensures that we create an outlet between our controller and view, and that it is treated as a global variable, allowing us to manipulate it in whichever functions we desire.

Finally, some code. Here are the steps we need to do:

1. Grab the image from our UIImageView and store it as a UIImage class (we will call this “theImage”)

2. Initialize CIFilter object. This is a class within Apple’s Core Image framework that has a dictionary that defines the attributes of a filter that it represents. There are many filters available, one of which is a color inversion filter.

3. Apply the CIFilter to “theImage”

4. Create a new UIImage to store the filtered image – let’s call it “newImage”

5. Show “newImage” on the UIImageView on our view

The code for the above steps are as follows:

let theImage = ourImageView.image //this takes the image currently loaded on our UIImageView

let filter = CIFilter(name: "CIColorInvert") //this creates a CIFilter with the attribute color invert

filter.setValue(CIImage(image: theImage), forKey: kCIInputImageKey) //this applies our filter to our UIImage

let newImage = UIImage(CIImage: filter.outputImage) //this takes our inverted image and stores it as a new UIImage

ourImageView.image = newImage //this shows our new inverted image on our UIImageView on our View

That’s it! The Core Image framework seems to be a very powerful one, and you definitely have to read through the documentation at least once. Here’s a link. Strangely, the Core Image framework seems to be automatically included when creating a viewController.swift file (I didn’t have to do a ‘import CoreImage’ statement). I wonder if this is the case.