Load NSImage into QPixmap or QImage

I have an NSImage pointer from a platform SDK, and I need to load it into Qt's QImage class. To make things easier, I can create a QImage from a CGImageRef by using QPixmap as an intermediate format, like this:

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

However, I cannot find a way to convert from an NSImage to a CGImageRef. Several other people have had the same problem, but I have yet to find a solution.

There is the CGImageForProposedRect method, but I can't seem to get it to work. I'm currently trying this (img is my NSImage ptr):

CGImageRef ir = [img CGImageFirProposedRect:0:0:0];

Any ideas?

Answers


NSImage is a high level image wrapper that might contain more than one image (thumbnails, different resolutions, vector representations, ...) and does a lot of caching magic. A CGImage on the other hand is one plain bitmap image. Since NSImage is a so much richer object, there’s no easy way of converting in between the two.

To get a CGImageRef from an NSImage you have some options:

  1. Manually select an NSBitmapImageRep from the NSImage (using [img representations]) and get the CGImage from that.
  2. Setup a graphics context (CGBitmapContextCreate), draw the image into that, and create a CGImage from this context.
  3. Use the new Snow Leopard API to create the CGImage directly from the NSImage: [img CGImageForProposedRect:NULL context:nil hints:nil]

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

Need Your Help

What is the required size of an AES key in this code?

java android encryption aes

In the code below I'm initializing the security key from an external class. Is it necessary to use the security key length of 16? Any possibility to use the smaller length byte?

Two-Way Binding Of VerticalOffset Property on ScrollViewer?

c# silverlight xaml

I have a View and a ViewModel in Silverlight 3.0.