在Mac OS X上从Cocoa中的NSImage获取CGIImageRef

Mik*_*012 4 macos cocoa nsimage

我需要从NSImage获取CGIImageRef.有没有一种简单的方法在Cocoa for Mac OS X中执行此操作?

Aze*_*utt 15

很难错过:

- [NSImage CGImageForProposedRect:context:提示:]

  • FWIW,这只适用于Mac OS X 10.6或更高版本. (4认同)

Ben*_*itz 5

如果您需要定位Mac OS X 10.5或任何其他以前的版本,请改用以下代码段.如果你不这样做,那么NSD的答案是正确的方法.

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;
}
Run Code Online (Sandbox Code Playgroud)

如果您的图像来自文件,您可能最好使用图像源将数据直接加载到CGImageRef中.