Sunday 1 April 2012

CoreImage with MonoTouch (example)

In response to a question on the mailing list over the weekend I put together a quick example of using CoreImage in MonoTouch to adjust the Contrast, Saturation and Brightness of an image. It looks like this:
CoreImage with MonoTouch
The code is available in a gist; to use simply create a new MonoTouch Empty iPhone Project and paste in the code/create the files.
It initially uses a supplied image but you can take a photo with the camera and manipulate that instead. NOTE that when you take a camera image, a 'display copy' is made (scaled down to screen resolution) and the Contrast/Saturation/Brightness changes you make are applied to the scaled-down copy to ensure the UI is responsive and avoid memory issues. If you choose to save the image, the C/S/B values are re-applied to the original image before being saved, so you get an 'original resolution' verison saved to the Camera Roll.

There is also a CoreImage project on Xamarin's github which includes examples of many more CIFilters (see also Apple's docs). Plus there's a Sepia-tone example in the MonoTouch iOS5 doc.

FYI using CIFilters with MonoTouch is very simple as this method shows:
// the CoreImage filter  
CIColorControls colorCtrls;
// apply to an image
UIImage AdjustImage (UIImage image) {
   if (colorCtrls == null)
      colorCtrls = new CIColorControls () {
         Image = CIImage.FromCGImage (image.CGImage),
         Brightness = sliderB.Value, 
         Saturation = sliderS.Value, 
         Contrast = sliderC.Value
      };
   else {
      colorCtrls.Brightness = sliderB.Value; 
      colorCtrls.Saturation = sliderS.Value; 
      colorCtrls.Contrast = sliderC.Value;
      colorCtrls.Image = CIImage.FromCGImage(image.CGImage);
   }
   var output = colorCtrls.OutputImage;
   var context = CIContext.FromOptions (null);
   var result = context.CreateCGImage (output, output.Extent);
   colorCtrls = null;
   return UIImage.FromImage(result);
}