views:

506

answers:

2

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...

+2  A: 

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.

pheelicks
Yeah, but don't call `TIFFRepresentation` hundreds of times. Depending on the `NSImage`, it can end up creating a full, uncompressed copy of the image data in memory.
Alex
interesting. I'll try that and let you know.
Brian Postow
Excellent, this seems to work thanks!
Brian Postow
This is less good for both performance and predictability than Peter's solution. If the image has multiple representations (e.g. a 16x16 version and a 128x128 version), which do you get this way? Undefined.
Ken
+2  A: 
  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.
Peter Hosey
I've tried this, and it either seems to not work with 1 bit B/W images (macs for some reason really don't like to deal with CCITT TIFFs...) or loses resolution... Since I have an NSImage, I'm not sure that I actually can FIND the resolution to figure out how to make a better graphics context...
Brian Postow
Look in the image's `representations` array. One of them should be a bitmap image rep. You can ask that object for the size in pixels (as opposed to points), among other raster-related facts.
Peter Hosey