一尘不染

无法使用CIFilter从CIImage提取UIImage

swift

我有这个新的iOS 8 Swift项目,在它的一个视图控制器中,我必须设置图像。但是,我想在将图像CIFilter发送到视图之前更改图像的对比度:

这是我的代码:

view = UIImageView(frame:CGRectMake(0, 0, 200, 200))

var lecturePicture = UIImage(named: "placeholder")            
var beginImage = lecturePicture?.CIImage
var controlsFilter = CIFilter(name: "CIColorControls")

controlsFilter.setValue(beginImage, forKey: kCIInputImageKey)
controlsFilter.setValue(1.5, forKey: "inputContrast")

var displayImage = UIImage(CIImage: controlsFilter.outputImage) // breakpoint
(view as UIImageView!).image = displayImage

好吧,我只是获取图像,对其进行转换,然后将转换后的版本作为UIImage并将其设置回我的视图。

但是我只得到一个错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

有人可以告诉我我在做什么错吗?


阅读 255

收藏
2020-07-07

共1个答案

一尘不染

差不多了

controlsFilter.setValue(beginImage, forKey: kCIInputImageKey)  // here you did it the right way
controlsFilter.setValue(1.5, forKey: "inputContrast")       // you should keep the same approach here

迅捷2

let lecturePicture = UIImage(data: NSData(contentsOfURL: NSURL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!)!)!
let controlsFilter = CIFilter(name: "CIColorControls")
let beginImage = CIImage(image: lecturePicture)
controlsFilter.setValue(beginImage, forKey: kCIInputImageKey)
controlsFilter.setValue(1.5, forKey: kCIInputContrastKey)
let displayImage = UIImage(CGImage: CIContext(options: nil).createCGImage(controlsFilter.outputImage, fromRect:controlsFilter.outputImage.extent()))!
displayImage

Swift 3或更高版本

let lecturePicture = UIImage(data: try! Data(contentsOf: URL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!))!
let controlsFilter = CIFilter(name: "CIColorControls")!
let beginImage = CIImage(image: lecturePicture)
controlsFilter.setValue(beginImage, forKey: kCIInputImageKey)
controlsFilter.setValue(1.5, forKey: kCIInputContrastKey)
let displayImage = UIImage(cgImage: CIContext(options: nil).createCGImage(controlsFilter.outputImage!, from: controlsFilter.outputImage!.extent)!)
displayImage
2020-07-07