2010-03-18 65 views
2

我有一个来自平台SDK的NSImage指针,我需要将它加载到Qt的QImage类中。为了方便起见,我可以使用的QPixmap作为中间格式,这样创建一个从CGImageRef一个QImage的:加载NSImage到QPixmap或QImage中

CGImageRef myImage = // ... get a CGImageRef somehow. 
QImage img = QPixmap::fromMacCGImageRef(myImage).toImage(); 

不过,我不能找到一种方法,从NSImage中转换为CGImageRef。 Severalother people有同样的问题,但我还没有找到解决方案。

CGImageForProposedRect方法,但我似乎无法得到它的工作。我目前正在尝试这个(img是我的NSImage ptr):

任何想法?

回答

3

NSImage是一个高级别的图像包装,可能包含多个图像(缩略图,不同的分辨率,矢量表示,...),并做了大量的缓存魔术。 A CGImage另一方面是一个简单的位图图像。由于NSImage是一个非常丰富的对象,因此两者之间没有简单的转换方法。

要从NSImage中得到CGImageRef你有一些选择:

  1. 手动选择从NSImage(使用[img representations])的NSBitmapImageRep,并从该CGImage
  2. 设置图形上下文(CGBitmapContextCreate),将图像绘制到该图像中,并从此上下文创建CGImage
  3. NSImage使用新的雪豹API来创建CGImage直接:[img CGImageForProposedRect:NULL context:nil hints:nil]
+0

完美的作品,谢谢! – Thomi 2010-03-18 11:44:36

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]; 
相关问题