Getting a CGImage from CIImage

tagyro picture tagyro · Jan 18, 2013 · Viewed 27.1k times · Source

I have a UIImage which is loaded from a CIImage with:

tempImage = [UIImage imageWithCIImage:ciImage];

The problem is I need to crop tempImage to a specific CGRect and the only way I know how to do this is by using CGImage. The problem is that in the iOS 6.0 documentation I found this:

CGImage
If the UIImage object was initialized using a CIImage object, the value of the property is NULL.

A. How to convert from CIImage to CGImage? I'm using this code but I have a memory leak (and can't understand where):

+(UIImage*)UIImageFromCIImage:(CIImage*)ciImage {  
    CGSize size = ciImage.extent.size;  
    UIGraphicsBeginImageContext(size);  
    CGRect rect;  
    rect.origin = CGPointZero;  
    rect.size   = size;  
    UIImage *remImage = [UIImage imageWithCIImage:ciImage];  
    [remImage drawInRect:rect];  
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();  
    UIGraphicsEndImageContext();  
    remImage = nil;  
    ciImage = nil;  
    //
    return result;  
}

Answer

skymook picture skymook · Aug 22, 2017

Swift 3, Swift 4 and Swift 5

Here is a nice little function to convert a CIImage to CGImage in Swift.

func convertCIImageToCGImage(inputImage: CIImage) -> CGImage? {
    let context = CIContext(options: nil)
    if let cgImage = context.createCGImage(inputImage, from: inputImage.extent) {
        return cgImage
    }
    return nil
}