JustAnotherGuy
JustAnotherGuy

Reputation: 259

Set image contrast -- swift

I want to set up a function in swift that will set the contrast of an image to full/max.

func contrastImage(in image: UIImage) -> UIImage? {
    let outpic = image
    return outpic
}

I can't seem to figure out how to make this happen. Hopefully someone can help me, Thanks!

Upvotes: 3

Views: 3594

Answers (1)

Mike Henderson
Mike Henderson

Reputation: 2132

Use Core Image's CIFilter:

func increaseContrast(_ image: UIImage) -> UIImage {
    let inputImage = CIImage(image: image)!
    let parameters = [
        "inputContrast": NSNumber(value: 2)
    ]
    let outputImage = inputImage.applyingFilter("CIColorControls", parameters: parameters)

    let context = CIContext(options: nil)
    let img = context.createCGImage(outputImage, from: outputImage.extent)!
    return UIImage(cgImage: img)
}

Adjust inputContrast as you please: a value of 1 means no changes. Less than 1 mean desaturate. Greater than 1 means increasing the contrast.

Upvotes: 7

Related Questions