Skip to content

Applying CIFilter on Image in an UIImageView

February 1, 2012

In my latest App Filterastic I’m using CIFilter which was introduced in iOS 5. CIFilter class allows you to apply a filter to an CIImage. I will show you how you can use CIFilter with an UIImage object and in extend with an UIImageView.

//imgView is the UIImageView I’m using to display an UIImage to the user

//Put it all into an NSAutoreleasePool and release it when you are done or else the memory allocated by CIContext will increase every time you apply a filter
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

//First of all keep a copy of the original image orientation
//you’ll need it afterwards
UIImageOrientation originalOrientation = self.imgView.image.imageOrientation;

//Then you need to create the CIImage from the UIImage
//I used the CGImage property of the UIImage class and created the CIImage from the CGImage
CIImage *inputImage = [[CIImage alloc] initWithCGImage:[self.imgView.image CGImage]];

//Then create the CIFilter you want
//I’m using sepia in this example
CIFilter adjustmentFilter = [CIFilter filterWithName:@"CISepiaTone"];
[adjustmentFilter setDefaults];
[adjustmentFilter setValue:inputImage forKey:@"inputImage"];
[adjustmentFilter setValue:[NSNumber numberWithFloat:1.0f] forKey:@”inputIntensity”];

// The output CIImage with the sepia effect applied
CIImage *outputImage = [adjustmentFilter valueForKey:@"outputImage"];

//Create a CIContext
CIContext* context = [CIContext contextWithOptions:nil];

//Create an CGImageRef from the output CIImage
CGImageRef imgRef = [context createCGImage:outputImage fromRect:outputImage.extent] ;

// Create an UIImage from the CGImageRef object with scale = 1.0 and the orientation of the original image
UIImage* img = [[UIImage alloc] initWithCGImage:imgRef scale:1.0 orientation:originalOrientation];

//Release the CGImageRef object
CGImageRelease(imgRef);

//set the UIImage object to the UIImageView
self.imgView.image = img;

// release stuff
[img release];
[inputImage release];
[pool release];

About these ads

From → Code Snippets

2 Comments
  1. Navn permalink

    Good one… But its not working with CILineOverlay CIFilter… Can u plz help me.. Thanks in advance…

  2. @Navn CILineOverlay isn’t supported in iOS yet, it’s only available on Mac OS X.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: