Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning an NSImage* into a CGImageRef?

Is there an easy way to do this that works in 10.5?

In 10.6 I can use nsImage CGImageForProposedRect: NULL context: NULL hints: NULL

If I'm not using 1b black and white images (Like Group 4 TIFF), I can use bitmaps, but cgbitmaps seem to not like that setup... Is there a general way of doing this?

I need to do this because I have an IKImageView that seems to only want to add CGImages, but all I've got are NSImages. Currently, I'm using a private setImage:(NSImage*) method that I'd REALLY REALLY rather not be using...

like image 737
Brian Postow Avatar asked Mar 30 '10 19:03

Brian Postow


2 Answers

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.

like image 84
pheelicks Avatar answered Sep 22 '22 06:09

pheelicks


[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.
like image 35
Peter Hosey Avatar answered Sep 22 '22 06:09

Peter Hosey