Getting a Black and White UIImage (Not Grayscale)

前端 未结 6 1702
独厮守ぢ
独厮守ぢ 2021-02-04 20:23

I need to get a pure black and white UIImage from another UIImage (not grayscale). Anyone can help me?

Thanks for reading.

EDITED:

Here

6条回答
  •  终归单人心
    2021-02-04 21:09

    With Swift 3, I was able to accomplish this effect by using CIFilters, first by applying CIPhotoEffectNoir (to make it grayscale) and then applying the CIColorControl filter with the kCIInputContrastKey input parameter set to a high value (i.e. 50). Setting the kCIInputBrightnessKey parameter will also adjust how intense the black-and-white contrast appears, negative for a darker image, and positive for a brighter image. For example:

    extension UIImage {
        func toBlackAndWhite() -> UIImage? {
            guard let ciImage = CIImage(image: self) else {
                return nil
            }
            guard let grayImage = CIFilter(name: "CIPhotoEffectNoir", withInputParameters: [kCIInputImageKey: ciImage])?.outputImage else {
                return nil
            }
            let bAndWParams: [String: Any] = [kCIInputImageKey: grayImage,
                                              kCIInputContrastKey: 50.0,
                                              kCIInputBrightnessKey: 10.0]
            guard let bAndWImage = CIFilter(name: "CIColorControls", withInputParameters: bAndWParams)?.outputImage else {
                return nil
            }
            guard let cgImage = CIContext(options: nil).createCGImage(bAndWImage, from: bAndWImage.extent) else {
                return nil
            }
            return UIImage(cgImage: cgImage)
        }
    }
    

提交回复
热议问题