20

I'm playing with the Core Image framework. As I understand, if I have an image (NSImage), it needs to be converted into CIImage, first. I can do that.

NSImage *im1 = [[NSImage alloc] initWithContentsOfFile:imagepath];
NSRect rect1;rect1.size.width = img1.size.width; rect1.size.height = img1.size.height;
CGImageRef imageRef1 = [img1 CGImageForProposedRect:&rect1 context:[NSGraphicsContext currentContext] hints:nil];
CIImage *ciimage = [CIImage imageWithCGImage:imageRef1];

I have a function that applies a Core Image filter to a core image (CIImage), which I want to test. And I want to add output image to a window as a subview. So I need NSImage. How can I convert this core image back into NSImage? If I ask Google, I don't get good results.

Thank you for your help.

1
  • A suggestion to make it a bit easier: remove line 2 and replace line 3 with: CGImageRef imageRef1 = [img1 CGImageForProposedRect:nil context:nil hints:nil]; Commented Jun 30, 2013 at 6:26

3 Answers 3

36

I haven't tested it, but I think this should do it:

CIImage *ciImage = ...;

NSCIImageRep *rep = [NSCIImageRep imageRepWithCIImage:ciImage];
NSImage *nsImage = [[NSImage alloc] initWithSize:rep.size];
[nsImage addRepresentation:rep];

In Swift:

let ciImage = ...
let rep = NSCIImageRep(ciImage: ciImage)
let nsImage = NSImage(size: rep.size)
nsImage.addRepresentation(rep)
0
14

In Swift:

var rep: NSCIImageRep = NSCIImageRep(ciImage: gaussianBlurFilter.outputImage)
var nsImage: NSImage = NSImage(size: rep.size)
nsImage.addRepresentation(rep)
1
  • First line should probably be: var rep: NSCIImageRep = NSCIImageRep(ciImage: ciimage) Commented Oct 1, 2018 at 15:14
1

There are filters that extend the size of the image quite a lot, like CIMotionBlur. For an original image size 5120x1440 I ended up with an image with an "extent" x,y,w,h = -126,-502,5184,2444. To convert that to NSImage I use:

CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef cg_img = [context createCGImage:img fromRect:CGRectMake(0, 0, size.width, size.height)];

NSImage *ns_img = [[NSImage alloc] initWithCGImage:cg_img size:NSZeroSize];
CGImageRelease(cg_img);  // Don't forget this! (memory leak)

Where size is the original image's size. I don't see another direct path form CIImage to NSImage that allows you to specify the origin within the CIImage, while the CGImageRef conversion does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.