将NSImage加载到QPixmap或QImage中

3

我有一个来自平台SDK的NSImage指针,需要将其加载到Qt的QImage类中。为了简化操作,我可以通过使用QPixmap作为中间格式,从CGImageRef创建QImage,像这样:

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

然而,我找不到将NSImage转换为CGImageRef的方法。许多人也面临同样的问题(链接1)(链接2),但我仍未找到解决方案。
CGImageForProposedRect方法,但我似乎无法让它正常工作。我当前正在尝试以下代码(img是我的NSImage指针):
CGImageRef ir = [img CGImageFirProposedRect:0:0:0];

任何想法?
2个回答

4

NSImage是一个高级的图像封装器,可能包含多个图像(缩略图,不同分辨率,矢量表示等),并进行了大量的缓存处理。而CGImage则是一种简单的位图图像,两者之间没有简便的转换方式。

如果要从NSImage获取CGImageRef,您有以下选项:

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

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];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接