How to make a custom CIFilter in Swift

Here’s an example Swift program which will swap the red and green components of an image, and save the output to a file. It uses a custom CIFilter, which uses a GLSL kernel, the source of which is embedded in the program.

import Foundation
import CoreImage
import AppKit
let kernels = CIKernel.kernels(with:
    "kernel vec4 swapRG(sampler image) { " +
    "  vec4 t = sample(image, samplerCoord(image)); float r = t.r; t.r = t.g; t.g = r; return t;" +
let myKernel = kernels[0]
class SwapRedAndGreenFilter : CIFilter {
    var inputImage:CIImage?
    override var outputImage: CIImage? {
        let src = CISampler(image: self.inputImage!)
        return self.apply(myKernel, arguments: [src], options: nil)
let nsImage = NSImage(contentsOfFile: "/Users/jim/Lenna.png")!
let cgImage = nsImage.cgImage(forProposedRect: nil, context: nil, hints: [:])!
let inputImage = CIImage(cgImage: cgImage)
let filter = SwapRedAndGreenFilter()
filter.setValue(inputImage, forKey: kCIInputImageKey)
let outputImage = filter.outputImage!
let rep = NSBitmapImageRep(ciImage: outputImage.cropping(to: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height)))
let imageData = rep.representation(using: NSBitmapImageFileType.PNG, properties: [:])!
try! imageData.write(to: URL.init(string: "file:/Users/jim/output.png")!, options: NSData.WritingOptions.atomic)
I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

Tagged . All content copyright James Fisher 2017. This post is not associated with my employer. Found an error? Edit this page.