Convert UIImage to grayscale keeping image quality

前端 未结 7 1197
难免孤独
难免孤独 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:27

    I'd use CoreImage, which may keep the quality.

    func convertImageToBW(image:UIImage) -> UIImage {
    
        let filter = CIFilter(name: "CIPhotoEffectMono")
    
        // convert UIImage to CIImage and set as input
    
        let ciInput = CIImage(image: image)
        filter?.setValue(ciInput, forKey: "inputImage")
    
        // get output CIImage, render as CGImage first to retain proper UIImage scale
    
        let ciOutput = filter?.outputImage
        let ciContext = CIContext()
        let cgImage = ciContext.createCGImage(ciOutput!, from: (ciOutput?.extent)!)
    
        return UIImage(cgImage: cgImage!)
    }
    

    Depending on how you use this code, you may want to create the CIContext outside of it for performance reasons.

提交回复
热议问题