Swift3和MacOS:如何直接从磁盘加载文件

Swift 3 and MacOS: how to load file directly from disk

我试图想出一个简单的命令行 macOS 应用程序,它将使用 Core Image 模糊输入图像并将其保存在磁盘上的某个位置,如下所示:

./my-binary /absolute/path/input.jpg /absolute/path/output.jpg

如何从绝对路径加载图像到 CIImage

我有以下代码:

let imageURL = Bundle.main.pathForImageResource("/absolute/path/input.jpg")
let ciImage = CIImage(contentsOf: imageURL)

但是 imageURL 在执行后保持 nil

您需要使用提供给命令行应用程序的路径,而不是使用 Bundle。为此,请使用 CommandLine.Arguments.

简单示例:

import Foundation
import CoreImage

let args = CommandLine.arguments

if args.count > 2 {
    let inputURL = URL(fileURLWithPath: args[1])
    let outputURL = URL(fileURLWithPath: args[2])
    if let inputImage = CIImage(contentsOf: inputURL) {
        // use the CIImage here
        // save the modified image to outputURL
    }
    exit(EXIT_SUCCESS)
} else {
    fputs("Error - Not enough arguments\n", stderr)
    exit(EXIT_FAILURE)
}