简体   繁体   中英

After applying CIFilter image got bigger no matter what I do

I read latest know-hows about applying CIFilter to UIImage and display it back. However I still get my image bigger than the original, don't know why. Maybe I'm missing some scaling factor?.

This is my screen with plain UIImageView and some image. The only constraints are center X/Y to superview.

Screenshot before applying filter

在此处输入图片说明

However I've added this code in viewDidLoad() :

let ciContext = CIContext(options: nil)
let coreImage = CIImage(image: ledImageView.image!)

let filter = CIFilter(name: "CIExposureAdjust")
filter!.setValue(coreImage, forKey: kCIInputImageKey)
filter!.setValue(1.5, forKey: kCIInputEVKey)

let filteredImageData = filter?.outputImage as! CIImage
let filteredImageRef = ciContext.createCGImage(filteredImageData, from: filteredImageData.extent)

ledImageView.image = UIImage(cgImage: filteredImageRef!)

I get a result other than expected (yes, the filter is applied but size is broken). What did I do wrong?

Screenshot after applying filter

在此处输入图片说明

Thats strange,

what are the values of the extends of the input and output image ? Do they match ?

You could try this

// crop the output image to the input's image extend
let croppedImage = filteredImageData.cropped(to: coreImage.extent)
let result = UIImage(ciImage: croppedImage)

I found both root cause of the issue and the solution. Apparently final UIImage was lacking of scale and imageOrientation . The original (source) image had scale == 3.0 while image after processing stayed with scale == 1.0 .

Here is the proper source code for this:

let ciContext = CIContext(options: nil)
let coreImage = CIImage(image: sourceImageView.image!)

let srcScale = sourceImageView.image.scale // <-- keep this value
let srcOrientation = sourceImageView.image.imageOrientation // <-- keep that value

let filter = CIFilter(name: "CIExposureAdjust")
filter!.setValue(coreImage, forKey: kCIInputImageKey)
filter!.setValue(1.5, forKey: kCIInputEVKey)

let filteredImageData = filter?.outputImage as! CIImage
let filteredImageRef = ciContext.createCGImage(filteredImageData, from: filteredImageData.extent)

// use this constructor with scale/orientation values
ledImageView.image = UIImage(cgImage: filteredImageRef!, scale: srcScale: orientation: srcOrientation)

Now the result is as bellow :)

Fixed image on ViewController

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM