CIFilter output image nil

后端 未结 2 1166
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 22:24

I am using core image and I am applying a CIFilter sepia tone to my image. I run a filter once in viewDidLoad and then immediately call another function that adds the filter

相关标签:
2条回答
  • 2020-12-03 23:01

    You cannot call UIImage(CIImage:) and use that UIImage as the image of a UIImageView. UIImageView requires a UIImage backed by a bitmap (CGImage). A UIImage instantiated with CIImage has no bitmap; it has no actual image, it's just a set of instructions for applying a filter. That is why your UIImageView's image is nil.

    0 讨论(0)
  • 2020-12-03 23:17

    A couple of things here:

    1) Using the CIImage constructor to create a CIImage based on a non CIImage backed UIImage is dangerous and will return nil or an empty CIImage.

    2) When creating the image back I'd suggest you to use CIContext instead of UIImage(CIImage:).

    Example:

    class ViewController: UIViewController {
        @IBOutlet weak var myimage: UIImageView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            myimage.backgroundColor = UIColor.redColor()
    
            self.applyFilter()
            self.applyFilter()
        }
    
        func applyFilter(){
            let image = CIImage(CGImage: myimage.image?.CGImage)
            let filter = CIFilter(name: "CISepiaTone")
            filter.setDefaults()
            filter.setValue(image, forKey: kCIInputImageKey)
    
            let context = CIContext(options: nil)
            let imageRef = context.createCGImage(filter.outputImage, fromRect: image.extent())
            myimage.image = UIImage(CGImage: imageRef)
        }
    }
    
    0 讨论(0)
提交回复
热议问题