Adding a filter to an image in Xcode: CIImage and CIFilter in iOS



This is a quick and simple post to help you in the first steps of using image filters.

(1) create an image view (imageView) and hook it up to the .h file of your view controller using the storyboard for your project

(2) import the Core Image framework into your header file with #import <CoreImage/CoreImage.h> and add the framework to the "Linked Frameworks and Libraries" of your project target

(2) synthesize the image view in your .m file

(3) drag an image (image.jpg) into your project

(4) replace the viewDidLoad code of your view controller with this (reading the green comments as you do so)

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
 
    // Create a path to the image we want to manipulate
    NSString *filePath =
    [[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"];
    NSURL *fileNameAndPath = [NSURL fileURLWithPath:filePath];
 
    // Load the image as a CIImage
    CIImage *newImage =
    [CIImage imageWithContentsOfURL:fileNameAndPath];
   
    // Create a CIFilter using the image and one of Apple's document filters
    CIFilter *invertColour = [CIFilter filterWithName:@"CIColorInvert" keysAndValues:@"inputImage", newImage, nil];
   
    // Create a pointer to the image output by the filter
    CIImage *filteredImage = [invertColour outputImage];
   
   
    UIImage *newImg = [UIImage imageWithCIImage:filteredImage];
   
    [imageView setImage:newImg];
   

   
}


(5) Hit run

There are far more image filters you can play around with here, but not all work in iOS 5 and 6, while some are OS X only, so make sure to check.





Comments