Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
810 views
in Technique[技术] by (71.8m points)

ios - Can't extract UIImage from CIImage with CIFilter

I have this new iOS 8 Swift project and in one of its view controllers I have to set the image. However, I wanna change the contrast of the image using CIFilter before sending it to the view:

So this is my code:

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

Well, I'm simply getting an image, applying a transformation to it and then get the transformed version as a UIImage and setting it back to my view.

But I only get an error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Can someone please tell me what am I doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You almost got it.

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

Swift 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 or later

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...