反转UIImage后,为什么CIImage为零?

时间:2018-10-31 22:31:34

标签: swift image

我这里有一个非常特殊的问题,在我将UIImage反转后,我将UIImage转换为CIImage。这是代码:

let imageFromBuffer1 = self.imageInvert(image: self.imageFromBuffer)
let ciImage = CIImage(image: imageFromBuffer1)

因此,在上面的代码中,出于某些奇怪的原因,ciImage为nil。有人可以解释一下,还是告诉我要怎么做才能将UIImage转换为CIImage?

这是我在上面使用的求反函数:

func imageInvert(image: UIImage) -> UIImage{
    let beginImage = CIImage(image: image)
    var newImage = UIImage()
    if let filter = CIFilter(name: "CIColorInvert") {
        filter.setValue(beginImage, forKey: kCIInputImageKey)
        let ciImage = filter.outputImage
        newImage = UIImage(ciImage: ciImage!)

    }
    else{
        print("filter does not exist")
        newImage = image
    }

    return newImage
}

1 个答案:

答案 0 :(得分:2)

由于将图像从一种形式转换为另一种形式时,某些数据可能会被修改,丢失或不使用。例如,当您从资产中加载UIImage时,它可能会比其显示的视图大。图形引擎最好将图像显示得尽可能真实。但是,可能不会使用某些基础图像数据,对于压缩的jpeg图像尤其如此。与其来回转换图像,不如考虑转换图像所处的当前上下文:

ViewController.swift

import UIKit

class ViewController: UIViewController {

    lazy var imageView = UIImageView(frame: self.view.frame)

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(imageView)

        let tap = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
        imageView.addGestureRecognizer(tap)
        imageView.isUserInteractionEnabled = true
        imageView.contentMode = .scaleAspectFit
        // https://en.wikipedia.org/wiki/File:Meisje_met_de_parel.jpg
        imageView.image = UIImage(named: "Meisje_met_de_parel.jpg")

    }

    func invert(image: UIImage) -> UIImage? {

        let ciImage = CIImage(image: image)
        var newImage:UIImage? = nil
        guard let filter = CIFilter(name: "CIColorInvert") else {return image}
        filter.setValue(ciImage, forKey: kCIInputImageKey)
        let context = CIContext(options: nil)

        if let outputImage = filter.outputImage, let cgImage = context.createCGImage(outputImage, from: outputImage.extent) {
            newImage = UIImage(cgImage: cgImage)
        }

        return newImage

    }

    @objc func imageViewTapped() {
        if let image = self.imageView.image {
            let invertedImage = self.invert(image: image)
            DispatchQueue.main.async {
                self.imageView.image = invertedImage
            }
        }

    }

}