Convert between NSImage and CIImage in Swift
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:
- Uses NSImage to load a file
- Displays the NSImage in an NSImageView.
- Converts the NSImage to a CIImage.
- Runs a custom CIFilter on the CIImage.
- Converts the CIImage output back to an NSImageView.
- 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.
That’s it for today!