Swift 彩色照片转换成黑白照片

使用滤镜调节照片的饱和度、亮度和对比度值,再调整曝光度实现效果:

Swift 彩色照片转换成黑白照片_第1张图片
原图

Swift 彩色照片转换成黑白照片_第2张图片
处理后的

CIFilter的CIColorControls调整饱和度,亮度和对比度值。
kCIInputSaturationKey 饱和度
kCIInputBrightnessKey 亮度
kCIInputContrastKey 对比度

CIFilter的CIExposureAdjust曝光调整
kCIInputEVKey 曝光度

extension UIImage {
    func lj_blackAndWhite() -> UIImage? {
        guard let beginImage = CIImage(image: self) else {
            return nil
        }
        let parameters = [kCIInputImageKey      : beginImage,
                          kCIInputBrightnessKey : 0.0,
                          kCIInputContrastKey   : 1.1,
                          kCIInputSaturationKey : 0.0] as [String : Any]
        
        let blackAndWhite = CIFilter(name: "CIColorControls",
                                     withInputParameters: parameters)?.outputImage
        let outputParam = [kCIInputImageKey : blackAndWhite as Any,
                           kCIInputEVKey: 0.7] as [String : Any]
        let output = CIFilter(name: "CIExposureAdjust", withInputParameters: outputParam)?.outputImage
        guard let outputCI = output else {
            return nil
        }
        let context = CIContext(options: nil)
        guard let cgimage = context.createCGImage(outputCI, from: outputCI.extent) else {
            return nil
        }
        return UIImage(cgImage: cgimage, scale: 0, orientation: self.imageOrientation)
    }
}

你可能感兴趣的:(Swift 彩色照片转换成黑白照片)