How to Convert UIImage to CIImage and vice versa

CIImage *ciImage = [UIImage imageNamed:@"test.png"].CIImage;
UIImage *uiImage = [[UIImage alloc] initWithCIImage:ciImage];

To fix the case where myUIImage.CIImage returns nil like [UIImageView image], you can instead do [CIImage imageWithCGImage:myUIImage.CGImage] – Dylan Hand

Swift version:

let ciImage = UIImage(named: "test.png")!.ciImage
let uiImage = UIImage(ciImage: ciImage)

To fix the case where myUIImage.ciImage returns nil like you can instead do CIImage(cgImage: myUIImage!.cgImage!).


While Changxing Wang's answer is effectively correct, Apple says that UIImage.CIImage won't always work. Specifically, from PocketCoreImage:

// Create a CIImage from the _inputImage.  While UIImage has a property returning
// a CIImage representation of it, there are cases where it will not work.  This is the
// most compatible route.
_filteredImage = [[CIImage alloc] initWithCGImage:_inputImage.CGImage options:nil];

Apple also uses the following, which DOESN'T work for me:

[UIImage imageWithCIImage:_filteredImage] 

My personal implementation, adapted from this post does work for me:

// result is a CIImage, output of my filtering.  
// returnImage is (obviously) a UIImage that I'm going to return.
CIContext *context = [CIContext contextWithOptions:nil];
UIImage *returnImage = 
[UIImage imageWithCGImage:[context createCGImage:result fromRect:result.extent]];

This is most compatibile way of doing it:

UIImage* u =[UIImage imageNamed:@"image.png"];
CIImage* ciimage = [[CIImage alloc] initWithCGImage:u.CGImage];

now use ciimage...

and Swift version:

let i1 = UIImage(named: "testImage")
if let cgi1 = i1?.cgImage {
   let ci = CIImage(cgImage: cgi1)
   //use ci
}

(fixed typo in the if let statement)