如何解决由于 macOS 应用程序上的 CIFilter 导致的错误

How to solve error due to CIFilter on macOS app

我是 macOS 应用程序的新手,但 A 已经完成了一个 iOS 应用程序。 我会尝试将图像转换为灰度

编译没问题,但我在“filter.outputImage”

处遇到 运行 错误

错误是:线程 1:“-[NSImage imageByColorMatchingWorkingSpaceToColorSpace:]:无法识别的选择器发送到实例 0x60000201e4e0”

怎么了?

import Cocoa
import AppKit

class ViewController: NSViewController {

@IBOutlet weak var Load: NSButton!
@IBOutlet weak var ImageSource: NSImageView!
@IBOutlet weak var ImageNG: NSImageView!


func grayscale(image: NSImage) -> NSImage? {
    
    let width = image.size.width
    let height = image.size.height
    let cgsize = CGSize (width: width, height: height)
    
    let context = CIContext(options: nil)
    if let filter = CIFilter(name: "CIPhotoEffectMono") { //CIPhotoEffectNoir  CIPhotoEffectMono  CIPhotoEffectTonal CIPixellate
        filter.setValue(image, forKey: kCIInputImageKey)
        
        if let output = filter.outputImage {
            if let cgImage = context.createCGImage(output, from: output.extent) {
                return NSImage(cgImage : cgImage, size: cgsize)
            }
        }
    }
    return nil
}

@IBAction func LoadButtonClicked(_ sender: Any) {
    
    ImageSource.image = NSImage(named:"IMAGE")
    let imageNG = grayscale(image:  ImageSource.image! )
    ImageNG.image = imageNG
    
}

override func viewDidLoad() {
    super.viewDidLoad()
}

override var representedObject: Any? {
    didSet {
    }
}

}

kCIInputImageKey 的值是一个 CIImage 对象,而不是 NSImagehttps://developer.apple.com/documentation/coreimage/kciinputimagekey.

也许是这样的:

if let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) {
    filter.setValue(CIImage(cgImage: cgImage), forKey: kCIInputImageKey)
}