Search code examples
macosswift2nsimage

Mac OS Xcode Swift 2.2 Combine 2 or more NS images into a one new NSImage


I am looking for example code how to merge NSImages into one new NSImage for Mac OS (not Iphone IOS). Thx


Solution

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