Getting CGIImageRef from NSImage in Cocoa on Mac OS X

I need to get CGIImageRef from NSImage. Is there an easy way to do this on Cocoa for Mac OS X?

+4
source share
2 answers

If you need to target Mac OS X 10.5 or any other previous version, use the following snippet instead. If you do not, then the NSD answer is the right way.

CGImageRef CGImageCreateWithNSImage(NSImage *image) { NSSize imageSize = [image size]; CGContextRef bitmapContext = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, 8, 0, [[NSColorSpace genericRGBColorSpace] CGColorSpace], kCGBitmapByteOrder32Host|kCGImageAlphaPremultipliedFirst); [NSGraphicsContext saveGraphicsState]; [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:bitmapContext flipped:NO]]; [image drawInRect:NSMakeRect(0, 0, imageSize.width, imageSize.height) fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0]; [NSGraphicsContext restoreGraphicsState]; CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext); CGContextRelease(bitmapContext); return cgImage; } 

If your image comes from a file, you might be better off using an image source to load data directly into CGImageRef.

+5
source

All Articles