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

问题描述 投票:0回答:2

我有以下代码可以运行:

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'

swift macos nsimage
2个回答
28
投票

您可以创建一个核心图像上下文并根据您的 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
        }
    }
}

0
投票

@leo-dabus 的答案的一个补充是在 2023 年开箱即用。使用

Downloads
文件夹而不是
Desktop
,并在
Target > Signing & Capabilities
中将文件访问权限设置为读/写:

© www.soinside.com 2019 - 2024. All rights reserved.