从CIImage获取CGImage

我有一个UIImage从CIImage加载:

tempImage = [UIImage imageWithCIImage:ciImage];

问题是我需要裁剪tempImage到一个特定的CGRect和我知道如何做到这一点的唯一方法是通过使用CGImage 。 问题是,在iOS 6.0文档中,我发现这个:

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

A.如何将CIImage转换为CGImage? 我正在使用这个代码,但我有一个内存泄漏(并不明白在哪里):

 +(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; } 

请参阅CIContext文档:fromRect:

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

从答案到类似的问题: https : //stackoverflow.com/a/10472842/474896

此外,由于您有一个CIImage开始,您可以使用CIFilter实际上裁剪您的图像。

Swift 3.1

这里有一个很好的小函数来将CIImage转换为Swift中的CGImage

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

一些谷歌search后,我发现这种方法将CMSampleBufferRef转换为CGImage:

 + (CGImageRef)imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer // Create a CGImageRef from sample buffer data { CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); CVPixelBufferLockBaseAddress(imageBuffer,0); // Lock the image buffer uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0); // Get information of the image size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); size_t width = CVPixelBufferGetWidth(imageBuffer); size_t height = CVPixelBufferGetHeight(imageBuffer); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst); CGImageRef newImage = CGBitmapContextCreateImage(newContext); CGContextRelease(newContext); CGColorSpaceRelease(colorSpace); CVPixelBufferUnlockBaseAddress(imageBuffer,0); /* CVBufferRelease(imageBuffer); */ // do not call this! return newImage; } 

(但我closures了标签,所以我不知道从哪里得到)