我有一个来自平台SDK的NSImage指针,我需要将它加载到Qt的QImage类中。为了简化操作,我可以使用QPixmap作为中间格式从CGImageRef创建一个QImage,如下所示:
CGImageRef myImage = // ... get a CGImageRef somehow.
QImage img = QPixmap::fromMacCGImageRef(myImage).toImage();
但是,我找不到从NSImage转换为CGImageRef的方法。 Several other people遇到了同样的问题,但我还没有找到解决方案。
有CGImageForProposedRect
方法,但我似乎无法让它工作。我正在尝试这个(img
是我的NSImage ptr):
CGImageRef ir = [img CGImageFirProposedRect:0:0:0];
有什么想法吗?
答案 0 :(得分:3)
NSImage
是一个高级图像包装器,可能包含多个图像(缩略图,不同分辨率,矢量表示......),并且可以执行大量缓存操作。另一方面,CGImage
是一个普通的位图图像。由于NSImage
是一个更丰富的对象,因此在两者之间进行转换并不容易。
要从NSImage获得CGImageRef
,您有一些选择:
NSBitmapImageRep
手动选择NSImage
(使用[img representations]
)并从中获取CGImage
。CGBitmapContextCreate
),将图像绘制到图形上下文中,然后根据此上下文创建CGImage
。CGImage
创建NSImage
:[img CGImageForProposedRect:NULL context:nil hints:nil]
答案 1 :(得分:0)
// Sample to create 16x16 QPixmap with alpha channel using Cocoa
const int width = 16;
const int height = 16;
NSBitmapImageRep * bmp = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
pixelsWide:width
pixelsHigh:height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSDeviceRGBColorSpace
bitmapFormat:NSAlphaFirstBitmapFormat
bytesPerRow:0
bitsPerPixel:0
];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:bmp]];
// assume NSImage nsimage
[nsimage drawInRect:NSMakeRect(0,0,width,height) fromRect:NSZeroRect operation: NSCompositeSourceOver fraction: 1];
[NSGraphicsContext restoreGraphicsState];
QPixmap qpixmap = QPixmap::fromMacCGImageRef([bmp CGImage]);
[bmp release];