Convert UIImage to grayscale keeping image quality

前端 未结 7 1177
难免孤独
难免孤独 2020-12-08 19:42

I have this extension (found in obj-c and I converted it to Swift3) to get the same UIImage but grayscaled:

public fun         


        
相关标签:
7条回答
  • 2020-12-08 20:41

    A Swift 4.0 extension that returns an optional UIImage to avoid any potential crashes down the road.

    import UIKit
    
    extension UIImage {
        var noir: UIImage? {
            let context = CIContext(options: nil)
            guard let currentFilter = CIFilter(name: "CIPhotoEffectNoir") else { return nil }
            currentFilter.setValue(CIImage(image: self), forKey: kCIInputImageKey)
            if let output = currentFilter.outputImage,
                let cgImage = context.createCGImage(output, from: output.extent) {
                return UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation)
            }
            return nil
        }
    }
    

    To use this:

    let image = UIImage(...)
    let noirImage = image.noir // noirImage is an optional UIImage (UIImage?)
    
    0 讨论(0)
提交回复
热议问题