Converting CIImage Into NSImage
Asked Answered
T

3

18

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.

Taxable answered 30/6, 2013 at 2:46 Comment(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];Augean
N
35

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)
Negris answered 30/6, 2013 at 3:31 Comment(0)
L
13

In Swift:

var rep: NSCIImageRep = NSCIImageRep(ciImage: gaussianBlurFilter.outputImage)
var nsImage: NSImage = NSImage(size: rep.size)
nsImage.addRepresentation(rep)
Landslide answered 11/6, 2016 at 8:10 Comment(1)
First line should probably be: var rep: NSCIImageRep = NSCIImageRep(ciImage: ciimage)Ainslie
S
0

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.

Stamey answered 22/4, 2021 at 20:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.