将NSImage加载到QPixmap或QImage中

时间:2010-03-18 09:55:07

标签: c++ macos qt graphics

我有一个来自平台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];

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

NSImage是一个高级图像包装器,可能包含多个图像(缩略图,不同分辨率,矢量表示......),并且可以执行大量缓存操作。另一方面,CGImage是一个普通的位图图像。由于NSImage是一个更丰富的对象,因此在两者之间进行转换并不容易。

要从NSImage获得CGImageRef,您有一些选择:

  1. NSBitmapImageRep手动选择NSImage(使用[img representations])并从中获取CGImage
  2. 设置图形上下文(CGBitmapContextCreate),将图像绘制到图形上下文中,然后根据此上下文创建CGImage
  3. 使用新的Snow Leopard API直接从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];