Turning an NSImage* into a CGImageRef?

不问归期 提交于 2019-11-28 18:52:15

Found the following solution on this page:

NSImage* someImage;
// create the image somehow, load from file, draw into it...
CGImageSourceRef source;

source = CGImageSourceCreateWithData((CFDataRef)[someImage TIFFRepresentation], NULL);
CGImageRef maskRef =  CGImageSourceCreateImageAtIndex(source, 0, NULL);

All the methods seem to be 10.4+ so you should be fine.

Peter Hosey

[This is the long way around. You should only do this if you're still supporting an old version of OS X. If you can require 10.6 or later, just use the CGImage method instead.]

  1. Create a CGBitmapContext.
  2. Create an NSGraphicsContext for the bitmap context.
  3. Set the graphics context as the current context.
  4. Draw the image.
  5. Create the CGImage from the contents of the bitmap context.
  6. Release the bitmap context.

As of Snow Leopard, you can just ask the image to create a CGImage for you, by sending the NSImage a CGImageForProposedRect:context:hints: message.

Here's a more detailed answer for using - CGImageForProposedRect:context:hints::

NSImage *image = [NSImage imageNamed:@"image.jpg"];

NSRect imageRect = NSMakeRect(0, 0, image.size.width, image.size.height);

CGImageRef cgImage = [image CGImageForProposedRect:&imageRect context:NULL hints:nil];

Just did this using CGImageForProposedRect:context:hints:...

NSImage *image; // an image
NSGraphicsContext *context = [NSGraphicsContext currentContext];
CGRect imageCGRect = CGRectMake(0, 0, image.size.width, image.size.height);
NSRect imageRect = NSRectFromCGRect(imageCGRect);
CGImageRef imageRef = [image CGImageForProposedRect:&imageRect context:context hints:nil];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!