- (CGImageRef)renderNSImageToCGImage:(NSImage *)image { if (!image) { return NULL; } NSSize imageSize = [image size]; // Create a CGBitmapContext CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef bitmapContext = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, 8, // bits per component 0, // bytes per row (0 lets the context calculate it) colorSpace, kCGImageAlphaNoneSkipFirst); CGColorSpaceRelease(colorSpace); if (!bitmapContext) { return NULL; } // Create an NSGraphicsContext for the bitmap context NSGraphicsContext *nsGraphicsContext = [NSGraphicsContext graphicsContextWithCGContext:bitmapContext flipped:NO]; // Save the current graphics context to restore it later NSGraphicsContext *previousContext = [NSGraphicsContext currentContext]; [NSGraphicsContext setCurrentContext:nsGraphicsContext]; // Draw the image into the context [image drawInRect:NSMakeRect(0, 0, imageSize.width, imageSize.height) fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1.0]; // Extract the CGImage from the bitmap context CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext); // Restore the previous graphics context [NSGraphicsContext setCurrentContext:previousContext]; // Clean up the bitmap context CGContextRelease(bitmapContext); return cgImage; // The caller now owns this CGImageRef and is responsible for releasing it }