3

I was reading an article about Core Image where I saw the following lines:

if let output = filter?.valueForKey(kCIOutputImageKey) as? CIImage {
    let cgimgresult = context.createCGImage(output, fromRect: output.extent)
    let result = UIImage(CGImage: cgimgresult)
    imageView?.image = result
}

As you can see, the CIImage instance is first converted into a CGImage instance and only then into a UIImage one. After doing some research I found out that it had something to do with the scale of the image within the image view's bounds.

I wonder, is that the only reason (having the right scale for display purposes) why we need to do all those conversions because there is already an initializer for UIImage that takes an instance of CIImage as an argument?

Tigran Iskandaryan
  • 1,371
  • 2
  • 14
  • 41
  • Yes you can display a ciimage initialising an UIImage object but you won't be able to get a data representation of that image object (ie.: JPEG or PNG) – Leo Dabus Aug 07 '18 at 17:42

1 Answers1

0

In the UIImage's reference that wrote

An initialized UIImage object. In Objective-C, this method returns nil if the ciImage parameter is nil.

and like @matt wrote here

UIImage's CIImage is not nil only if the UIImage is backed by a CIImage already (e.g. because it was generated by imageWithCIImage:).

So, the direct init

UIImage(ciImage: ciImage)

can be nil.

That's why we should be init the UIImage via the CGImage, not CIImage

Quoc Nguyen
  • 2,839
  • 6
  • 23
  • 28
  • 1
    Thanks for your answer. However, the second quote is about the property `ciImage` on `UIImage` instance, not its initialization. And in the doc it is said that the initializer can return nil, but it is only in case of `Objective-C`. In its declaration for `Swift`, the `init` can't fail, so it can't return nil. As far as I understand, you are trying to say that the reason for converting into `CGImage` is that the return value for `UIImage(ciImage:)` can be nil. But as I mentioned above, in case of `Swift` it is a wrong assumption. – Tigran Iskandaryan Aug 18 '18 at 19:56