Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a CGImage from CIImage

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;   } 
like image 288
tagyro Avatar asked Jan 18 '13 15:01

tagyro


People also ask

How do you convert CIImage to UIImage?

This is most compatibile way of doing it: UIImage* u =[UIImage imageNamed:@"image. png"]; CIImage* ciimage = [[CIImage alloc] initWithCGImage:u. CGImage];

What is a CGImage?

A bitmap image or image mask.

What is CIImage in Swift?

A representation of an image to be processed or produced by Core Image filters.

What is CIContext?

Overview. The CIContext class provides an evaluation context for Core Image processing with Quartz 2D, Metal, or OpenGL. You use CIContext objects in conjunction with other Core Image classes, such as CIFilter , CIImage , and CIColor , to process images using Core Image filters.


2 Answers

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 } 

Notes:

  • CIContext(options: nil) will use a software renderer and can be quite slow. To improve the performance, use CIContext(options: [CIContextOption.useSoftwareRenderer: false]) - this forces operations to run on GPU, and can be much faster.
  • If you use CIContext more than once, cache it as apple recommends.
like image 158
skymook Avatar answered Sep 21 '22 15:09

skymook


See the CIContext documentation for createCGImage:fromRect:

CGImageRef img = [myContext createCGImage:ciImage fromRect:[ciImage extent]]; 

From an answer to a similar question: https://stackoverflow.com/a/10472842/474896

Also since you have a CIImage to begin with, you could use CIFilter to actually crop your image.

like image 45
Joris Kluivers Avatar answered Sep 23 '22 15:09

Joris Kluivers