Convert between NSImage and CIImage in Swift

Gary Bartos
1 min readFeb 19, 2021

Recently I wanted to run some offline image processing tests in Mac OS rather than in iOS. That meant working with NSImage from AppKit rather than UIImage from UIKit. Image processing was implemented as a custom CIFilter from the Core Image framework.

The Mac OS test app does the following:

  1. Uses NSImage to load a file
  2. Displays the NSImage in an NSImageView.
  3. Converts the NSImage to a CIImage.
  4. Runs a custom CIFilter on the CIImage.
  5. Converts the CIImage output back to an NSImageView.
  6. Displays the filtered NSImage.

Here’s the plain text code implemented in Swift 5 (XCode 12) as an extension to NSImage.

import AppKit

extension NSImage {
/// Generates a CIImage for this NSImage.
/// - Returns: A CIImage optional.
func ciImage() -> CIImage? {
guard let data = self.tiffRepresentation,
let bitmap = NSBitmapImageRep(data: data) else {
return nil
}
let ci = CIImage(bitmapImageRep: bitmap)
return ci
}

/// Generates an NSImage from a CIImage.
/// - Parameter ciImage: The CIImage
/// - Returns: An NSImage optional.
static func fromCIImage(_ ciImage: CIImage) -> NSImage {
let rep = NSCIImageRep(ciImage: ciImage)
let nsImage = NSImage(size: rep.size)
nsImage.addRepresentation(rep)
return nsImage
}
}

And here’s a screenshot of the same.

NSImage extension to convert to and from CIImage

That’s it for today!

--

--

Gary Bartos

Founder of Echobatix, engineer, inventor of assistive technology for people with disabilities. Keen on accessible gaming. echobatix@gmail.com