thebucc
thebucc

Reputation: 207

Issue when creating CIImage from file

I get a nil no matter what I try to load a CIImage directly from file. However I can load the file into a UIImage and convert that to CIImage.

So, this works:

        let testUIImage = UIImage(named: "image_0001.jpg")!
        let testCIImage = CIImage(image: testUIImage)  // OK

but this doesn't:

        let testCIImage = CIImage(contentsOf: URL(string: "image_0001.jpg")!)  // returns nil

What am I doing wrong? Is it the URL?

Upvotes: 1

Views: 2232

Answers (2)

Jatin Kathrotiya
Jatin Kathrotiya

Reputation: 539

you need to give file url if your image inside main bundle then you can get url like below code

guard let url = Bundle.main.url(forResource:"image_0001", withExtension:"jpg") else {
  return 
}
let testCIImage = CIImage(contentsOf: url)

Upvotes: 5

vadian
vadian

Reputation: 285250

  1. UIImage(named: "name.ext") is a convenience initializer. It's a short form of

    guard let url = Bundle.main.url(forResource:"name", withExtension:"ext"),
          let data = try? Data(contentsOf: url),
          let image = UIImage(data: data) else { return nil }
    return image
    
  2. URL(string: expects a string representing a full URL starting with a scheme for example

    URL(string: "https://example.com/path/to/image_0001.jpg")
    

    or

    URL(string: "file:///Users/myuser/path/to/image_0001.jpg")
    

Upvotes: 0

Related Questions