2016-10-10 65 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