적당한 고통은 희열이다

- 댄 브라운 '다빈치 코드' 중에서

Swift iOS 앱 개발/실전 Swift

[Swift] UIImage grayscale 이미지 흑백 변환

hongssup_ 2023. 12. 27. 14:11
반응형

UIImage 를 흑백으로 변환하는 법

extension UIImage {
    func convertToGrayScale() -> UIImage {
        let context = CIContext(options: nil)
        if let currentFilter = CIFilter(name: "CIPhotoEffectTonal") {
            let input = CIImage(image: self)
            currentFilter.setValue(input, forKey: kCIInputImageKey)
            if let output = currentFilter.outputImage, let cgImage = context.createCGImage(output, from: output.extent) {
                return UIImage(cgImage: cgImage)
            }
        }
        return self
    }
}

 

사용할 수 있는 CIFilter 에는 여러가지가 있는데 다음은 Mono, Noir, Tonal 을 순서대로 사용한 예시 결과물이다. 

 

 

참고 : https://stackoverflow.com/questions/40178846/convert-uiimage-to-grayscale-keeping-image-quality

 

Convert UIImage to grayscale keeping image quality

I have this extension (found in obj-c and I converted it to Swift3) to get the same UIImage but grayscaled: public func getGrayScale() -> UIImage { let imgRect = CGRect(x: 0, y: 0, width: w...

stackoverflow.com

 

728x90
반응형