Swift on MacOS - 如何将NSImage保存到磁盘

Pon*_*ono 8 macros nsimage swift

我有以下代码工作:

let myImage = NSImage(named: "my-image.png")

filter.setValue(myImage, forKey: kCIInputImageKey)
filter.setValue(0.5, forKey: kCIInputIntensityKey)

let resultImage = filter.outputImage
Run Code Online (Sandbox Code Playgroud)

如何将过滤后的图像(作为PNG)保存到磁盘?请注意,这是一个MacOS版本,其中UIImage不可用(Xcode抛出:尝试导入时没有这样的模块'UIImage')

Leo*_*bus 15

您可以从ciimage过滤器结果创建Core Image Context和createCGImage.你可以这样做:

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")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您将需要这些扩展来获取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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 工作起来就像一个魅力。谢谢你! (2认同)