我有以下代码可以运行:
let myImage = NSImage(named: "my-image.png")
filter.setValue(myImage, forKey: kCIInputImageKey)
filter.setValue(0.5, forKey: kCIInputIntensityKey)
let resultImage = filter.outputImage
如何将过滤后的图像(作为 PNG)保存到磁盘?请注意,这是一个 MacOS 版本,其中 UIImage 不可用(Xcode 会在尝试导入时抛出:
No such module 'UIImage'
)
您可以创建一个核心图像上下文并根据您的 ciimage 过滤器结果创建CGImage。您可以按照以下步骤进行:
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let context = CIContext()
let desktopURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first!
guard
let filter = CIFilter(name: "CISepiaTone"),
let imageURL = Bundle.main.url(forResource: "my-image", withExtension: "png"),
let ciImage = CIImage(contentsOf: imageURL)
else { return }
filter.setValue(ciImage, forKey: kCIInputImageKey)
filter.setValue(0.5, forKey: kCIInputIntensityKey)
guard let result = filter.outputImage, let cgImage = context.createCGImage(result, from: result.extent)
else { return }
let destinationURL = desktopURL.appendingPathComponent("my-image.png")
let nsImage = NSImage(cgImage: cgImage, size: ciImage.extent.size)
if nsImage.pngWrite(to: destinationURL, options: .withoutOverwriting) {
print("File saved")
}
}
}
您将需要这些扩展来获取 png 表示数据,以将生成的图像写入磁盘:
extension NSImage {
var pngData: Data? {
guard let tiffRepresentation = tiffRepresentation, let bitmapImage = NSBitmapImageRep(data: tiffRepresentation) else { return nil }
return bitmapImage.representation(using: .png, properties: [:])
}
func pngWrite(to url: URL, options: Data.WritingOptions = .atomic) -> Bool {
do {
try pngData?.write(to: url, options: options)
return true
} catch {
print(error)
return false
}
}
}