Pono
Pono

Reputation: 11776

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

I'm trying to come up with a simple command-line macOS application which will blur an input image with Core Image and save it somewhere on disk like so:

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

How do I load an image from absolute path into CIImage?

I have the following code:

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

However the imageURL holds nil after executing.

Upvotes: 2

Views: 1302

Answers (1)

Eric Aya
Eric Aya

Reputation: 70094

Instead of using the Bundle you need to use the paths you are giving to your command line app. For this, use CommandLine.Arguments.

Simple example:

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)
}

Upvotes: 3

Related Questions