CIFilter输出图像为零

时间:2015-02-07 19:23:39

标签: ios swift core-image cifilter

我正在使用核心图像,我正在为我的图像应用CIFilter棕褐色调。我在viewDidLoad中运行一次过滤器,然后立即调用另一个再次添加过滤器的函数。出于某种原因,当我尝试访问输出图像时,应用程序崩溃并说输出图像为零。任何人都知道为什么会这样吗?

由于

    import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var myimage: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let image = CIImage(image: myimage.image)
        let filter = CIFilter(name: "CISepiaTone")
        filter.setDefaults()
        filter.setValue(image, forKey: kCIInputImageKey)
        myimage.image = UIImage(CIImage: filter.outputImage)
        self.reapplyFilter()
    }

        func reapplyFilter(){
            let image = CIImage(image: myimage.image)
            let filter = CIFilter(name: "CISepiaTone")
            filter.setDefaults()
            filter.setVa    lue(image, forKey: kCIInputImageKey)
    //ERROR HERE: fatal error: unexpectedly found nil while unwrapping an Optional value
            myimage.image = UIImage(CIImage: filter.outputImage)
//ERROR
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }



}

2 个答案:

答案 0 :(得分:10)

您无法调用UIImage(CIImage:)并将该UIImage用作UIImageView的图像。 UIImageView需要一个由位图(CGImage)支持的UIImage。用CIImage实例化的UIImage没有位图;它没有实际图像,它只是一组应用过滤器的指令。这就是你的UIImageView图像为零的原因。

答案 1 :(得分:8)

这里有几件事:

1)使用CIImage构造函数基于非CIImage支持的UIImage创建CIImage是危险的,并且将返回nil或空CIImage。

2)在创建图像时,我建议您使用CIContext而不是UIImage(CIImage :)。

示例:

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