PIYO - Tech & Life -

UIImageの明るさをCIFilterで調整するSwiftコード

Swift iOS
  • CIFilterを使う
  • CIColorControls
  • inputBrightnessに値を設定
  • 値は−1.01.0
import CoreImage

extention UIImage {
    func adjustBrightness(brightness: Double) -> UIImage? {
        let ciImage = CIImage(cgImage: self.cgImage!)

        let filter = CIFilter(name: "CIColorControls")
        filter?.setValue(ciImage, forKey: kCIInputImageKey)
        filter?.setValue(brightness, forKey: "inputBrightness")

        guard let newCIImage = filter?.outputImage else {
            return nil
        }

        let context = CIContext(options: nil)
        guard let cgImage = context.createCGImage(newCIImage, from: newCIImage.extent) else {
            return nil
        }
        return UIImage(cgImage: cgImage, scale: 1.0, orientation: .up)
    }
}

こんな感じで使える。

let image = UIImage(...)
let newImage = image.adjustBrightness(brightness: 0.5)