I am looking for example code how to merge NSImages into one new NSImage for Mac OS (not Iphone IOS). Thx
Asked
Active
Viewed 1,071 times
5
-
Thank you for your response. However the referenced code creates a CI image not the desired NSImage – FJC Jul 02 '16 at 19:39
-
i tried this link http://stackoverflow.com/questions/17386650/converting-ciimage-into-nsimage which did not work, Do you have a good link? – FJC Jul 02 '16 at 19:47
-
Even better, I'm writing an answer, I'm almost done. :) – Eric Aya Jul 02 '16 at 19:48
-
thx looking forward to it. – FJC Jul 02 '16 at 19:52
1 Answers
6
You can use the powerful filters from Core Image to merge two NSImages.
In this example we're using Core Image's "CIAdditionCompositing" filter.
First, make CIImages from the two NSImages you want to blend, for example using their URL:
let img1 = CIImage(contentsOfURL: yourFirstImageURL)
let img2 = CIImage(contentsOfURL: yourSecondImageURL)
Then initialize the CIFilter:
let filter = CIFilter(name: "CIAdditionCompositing")!
filter.setDefaults()
Merge the two images, you get to decide which one is in front of the other:
filter.setValue(img1, forKey: "inputImage")
filter.setValue(img2, forKey: "inputBackgroundImage")
let resultImage = filter.outputImage
Get back an NSImage:
let rep = NSCIImageRep(CIImage: resultImage!)
let finalResult = NSImage(size: rep.size)
finalResult.addRepresentation(rep)
finalResult // is your final NSImage
If you need to merge several images, simply take the result of the previous merge operation and add it again to another image using this same code.
Note: in this example I'm "force unwrapping" the optionals, for clarity. In your real code you should handle the possibility of failure and safely unwrap the optionals instead.

Eric Aya
- 69,473
- 35
- 181
- 253