2016-10-10 66 views
2

我想要想出一个简单的命令行macOS应用程序,它将使用Core Image将输入图像模糊并将其保存在磁盘上的某处:Swift 3和MacOS:如何直接从磁盘加载文件

./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

回答

3

不需要使用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) 
} 
+2

小鸡蛋里挑骨头:使用'EXIT_SUCCESS'和'EXIT_FAILURE'而不是'0'和'1'和打印错误消息到stderr,而不是标准输出的命令行工具。 –

+0

@MartinR好主意。完成。 – Moritz

+0

工作就像一个魅力。谢谢。 – Pono