CIFilter output image nil

独自空忆成欢 提交于 2019-11-28 12:11:15

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.

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)
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!