ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

iOS 5 | How-To Tutorial on Creating Core Image Applications for iPad, iPhone or iPod Touch

Updated on May 9, 2012
klanguedoc profile image

Kevin is Software Developer with 20 years experience designing and building business intelligence and system integration solutions.

The big difference to Core Image is that it is now available in the iOS 5 SDK. However you cannot create custom filters like you can using the Mac OSX 10.7 SDK version. You can however use a subset of existing filters to enhance images, photos and other graphic media. Third party filters can also be used, thus allowing you to create your own filters for re distribution. The framework provides powerful editing capabilities like enhance hues, vibrance or distortion.

The Core Image process works by making a copy of your original image and applying the changes to the copy. You can stack several filters together to create stunning transformations. When combined, the filters act as one so the effects are applied at the same time in near realtime. Each filter has its own parameters can be applied. You can also programmatically obtain information on which filter was applied to an image.

The Core Image Framework has 8 main classes and the also the Core Image Filters.

CIImage

CIImage represents the image that will undergo transformation. The image can be from a file, pixel data or created with UIImage.

CIFilter

The CIFilter class applies filters to an initial copy of the image, or input CIImage and transforms the copy by applying filters to the image and produces an output CIImage. The filters are key/value pairings that are applied to an image. Several filters can be combined to allow a user to completely transform the input image.

CIColor

The CIColor represents the different color transformations that can be applied to a CIImage. When applying a color, you can use a constant like colorWhite or colorBlue, or you can opt to use RGB values. The colors can be defined as -one to -four environmental dimension whose components different intensities. The color value range fro 0.0 to 1.0 where 0.0 is void of color and 1.0 is opaque.

CIContext

The CIContext is the context where the transformation is being applied using Quartz 2d or Open GL. The CIContext works in conjunction with the other classes in the framework to apply filters to transform the image.

CIDetector

The CIDetector can be used to find specific features in an image.

CIFaceFeature

This class has a narrow focus as it is used to detect specific features in faces in an image. For instance the class can find the eyes and mouth in a face in an image.

CIFeature

This class represent a portion of an image that has be defined with the CIDetector class.

CIVector

The CIVector manges to the vector coordinates on an image. This class is frequently used to pass x, y, z coordinates to the CIFilter class to apply a particular to a certain area of an image.

Sample Core Image App

Here is a small example on how to apply image filtering to photo image that is stored in a file. The app will apply a filter to invert the colors in the photo.

  • To start create a Single View project for the iPad and add the QuartzCore.framework and the CoreImage.framework to the Linked Frameworks and Libraries. Take a look at the screenshot (Figure 1) on how to add frameworks to a project.

Figure 1: Adding the CoreImage Frameworks to the project.
Figure 1: Adding the CoreImage Frameworks to the project.
  • Once the framework is added, drag the file to the Frameworks group. Then open the storyboard and add an UImageView Controller to the View Controller. You may need to resize to fit the screen or if you want to add a label. Figure 2 below is the UI for the sample app.

Figure 2: Storyboard Layout
Figure 2: Storyboard Layout

In this example, a filter will be applied to invert the colors of a supplied image. The best place to start building our application is in the klViewController.h header file. The code for the example is provided in listing 1.

Code Listing 1 - Core Image Example - klViewController Header

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <CoreImage/CoreImage.h>

@interface klViewController : UIViewController

@property(nonatomic, strong) NSString * file;
@property(nonatomic, strong) NSURL * imageFile;
@property(nonatomic, strong) CIImage * myImage;
@property(nonatomic, strong) CIImage * myImageOut;
@property(nonatomic, strong) CIFilter * filters;
@property(nonatomic, strong) CIContext * context;
@property(nonatomic, strong) UIImage * invertedImage;

@property (strong, nonatomic) IBOutlet UIImageView *ImageViewer;

-(void)LoadImage;

@end
  • For this example, we will need to create an instance variable for our file path which will be a NSString. We will use the NSBundle resourceForPath to get the path and filename of the image file that we will transform.
  • Next create an instance variable for the NSUrl which will represent the actual image file. The two CIImage instance methods are for the input and output images. The CIImage instance variable, myImage, will use the imageFile as an input and will apply a filter to a copy of the orignal.
  • Once the filter has been applied, the output CIImage, myImageOut will be assigned the result of the filtering and will passed to a CGImageRef instance variable that will be defined in the implementation file.
  • Finally the transformed image will be assigned to the UIImage and added to the UIImageView IBOutlet.
  • To create the IBOutlet connection, open the storyboard and select the Assistant Editor which will open the header file besides the Storyboard canvas. Perform a control+drag from the UIImageView to the header file. In the popup specify IBOutlet as a connection type and give our UIImageView an identifier like imageViewer. Figure 2 provides a screenshot of the process.

Figure 2: Create an IBOutlet connection for UIImageView
Figure 2: Create an IBOutlet connection for UIImageView

Next you will need to add some code to the loadImage method in the View Controller to get a handle on the image file and create an UIImage object. Notice in the code in listing 2 below that context instance variable is set to nil. This is because we will be using the default values, otherwise we could pass a NSDictionary of CIContext values to evaluate the CIImage that will be transformed by one or more filters. For the filter, we will use the CIColorInvert option but we could have chosen several others filters or for that matter added extra filters to apply a composite filtering. Once the filters are applied, the output is assigned to the myImageOut instance variable using the valueForKey:@"outputImage" option. Then the output image is passed to the CGImageRef which is a bitmap representation of our transformed image which will be added to the invertedImage instance variable. It is the UIImage's job to display image data and can use different sources to to display this data. It is in scope to NSData. Finally our UIImage to added to the UIImageView controller to be rendered on screen.

Code Listing 2 loadImage Implementation

-(void)loadImage{
   
    file =[[NSBundle mainBundle] pathForResource:@[md]me_at_peyto_lake[md] ofType:@[md]jpg[md]];
    imageFile = [NSURL fileURLWithPath:file];
    
    myImage = [CIImage imageWithContentsOfURL:imageFile];
    context = [CIContext contextWithOptions:nil];
    filters = [CIFilter filterWithName:@[md]CIColorInvert[md]
                         keysAndValues:kCIInputImageKey, myImage, nil];
    
    myImageOut =[filters valueForKey:@[md]outputImage[md]];
    CGImageRef imgReference = [context createCGImage:myImageOut fromRect:[myImageOut extent]];
    
    invertedImage = [UIImage imageWithCGImage:imgReference];
    
    [ImageViewer setImage:invertedImage];   
}

You can find a complete list of filters on the Apple web site: https://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CoreImageFilterReference/Reference/reference.html#//apple_ref/doc/uid/TP40004346

This is original file and the version that was transformed with the CIColorInvert filter:

Figure 3: This is the original file which is me at Peyto Lake in Alberta Canada
Figure 3: This is the original file which is me at Peyto Lake in Alberta Canada
Figure 4: This the same photo with the inverted colors.
Figure 4: This the same photo with the inverted colors.

CoreImage is an amazing framework and offers tremendous power and ressources to every developer. I invited you to further explore the framework and experiment with the different filters.

Comments

    0 of 8192 characters used
    Post Comment

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      5 years ago from Canada

      the sample code can be downloaded from www.iosdev101.com/downloads

    • profile image

      Pranav 

      5 years ago

      It is not worked for me. can you please give us your tutorial link. It will be better helpful.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)