Getting a CGImage from CIImage Getting a CGImage from CIImage ios ios

Getting a CGImage from CIImage


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.


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.


After some googling I found this method which converts a CMSampleBufferRef to a 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;}

(but I closed the tab so I don't know where I got it from)


matomo